0

Port base/watchdog to Linux.

BUG=4632

Review URL: http://codereview.chromium.org/11326
Patch from Pawel Hajdan Jr.

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@6004 0039d316-1c4b-4281-b951-d872f2087c98
This commit is contained in:
deanm@chromium.org
2008-11-25 22:46:59 +00:00
parent d8375fdbe8
commit 95ab1553ce
6 changed files with 70 additions and 97 deletions

@ -21,8 +21,8 @@ if env['PLATFORM'] == 'win32':
], ],
) )
# These base files work on *all* platforms; files that don't work # Some files from this list are not yet ported. They are removed from
# cross-platform live below. # the list, see code below.
input_files = [ input_files = [
'at_exit.cc', 'at_exit.cc',
'base_paths.cc', 'base_paths.cc',
@ -109,14 +109,11 @@ if env['PLATFORM'] in ('posix', 'darwin'):
'event_recorder.cc', 'event_recorder.cc',
'file_version_info.cc', 'file_version_info.cc',
# This group all depends on MessageLoop.
# We have an implementation of idle_timer, but it's unclear if we want it # We have an implementation of idle_timer, but it's unclear if we want it
# yet, so it's commented out for now. Leave this 'unported'. # yet, so it's commented out for now. Leave this 'unported'.
'idle_timer.cc', 'idle_timer.cc',
'object_watcher.cc', 'object_watcher.cc',
'watchdog.cc',
'resource_util.cc', # Uses HMODULE, but may be abstractable. 'resource_util.cc', # Uses HMODULE, but may be abstractable.
] ]

@ -114,7 +114,6 @@ if env['PLATFORM'] in ('posix', 'darwin'):
# yet, so it's commented out for now. Leave this 'unported'. # yet, so it's commented out for now. Leave this 'unported'.
'idletimer_unittest.cc', 'idletimer_unittest.cc',
'watchdog_unittest.cc',
'gfx/native_theme_unittest.cc', 'gfx/native_theme_unittest.cc',
] ]
for remove in to_be_ported_files: for remove in to_be_ported_files:

@ -4,8 +4,8 @@
#include "base/watchdog.h" #include "base/watchdog.h"
#include "base/compiler_specific.h"
#include "base/platform_thread.h" #include "base/platform_thread.h"
#include "base/string_util.h"
using base::TimeDelta; using base::TimeDelta;
using base::TimeTicks; using base::TimeTicks;
@ -15,42 +15,32 @@ using base::TimeTicks;
// Start thread running in a Disarmed state. // Start thread running in a Disarmed state.
Watchdog::Watchdog(const TimeDelta& duration, Watchdog::Watchdog(const TimeDelta& duration,
const std::wstring& thread_watched_name, const std::string& thread_watched_name,
bool enabled) bool enabled)
: lock_(), : init_successful_(false),
lock_(),
condition_variable_(&lock_), condition_variable_(&lock_),
state_(DISARMED), state_(DISARMED),
duration_(duration),
thread_watched_name_(thread_watched_name), thread_watched_name_(thread_watched_name),
handle_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST(delegate_(this, duration)) {
thread_id_(0) {
if (!enabled) if (!enabled)
return; // Don't start thread, or doing anything really. return; // Don't start thread, or doing anything really.
handle_ = CreateThread(NULL, // security init_successful_ = PlatformThread::Create(0, // Default stack size.
0, // Default stack size. &delegate_,
Watchdog::ThreadStart, &handle_);
reinterpret_cast<void*>(this), DCHECK(init_successful_);
CREATE_SUSPENDED,
&thread_id_);
DCHECK(NULL != handle_);
if (NULL == handle_)
return ;
ResumeThread(handle_); // WINAPI call.
} }
// Notify watchdog thread, and wait for it to finish up. // Notify watchdog thread, and wait for it to finish up.
Watchdog::~Watchdog() { Watchdog::~Watchdog() {
if (NULL == handle_) if (!init_successful_)
return; return;
{ {
AutoLock lock(lock_); AutoLock lock(lock_);
state_ = SHUTDOWN; state_ = SHUTDOWN;
} }
condition_variable_.Signal(); condition_variable_.Signal();
DWORD results = WaitForSingleObject(handle_, INFINITE); PlatformThread::Join(handle_);
DCHECK(WAIT_OBJECT_0 == results);
CloseHandle(handle_);
handle_ = NULL;
} }
void Watchdog::Arm() { void Watchdog::Arm() {
@ -75,8 +65,6 @@ void Watchdog::ArmAtStartTime(const TimeTicks start_time) {
// Disable watchdog so that it won't do anything when time expires. // Disable watchdog so that it won't do anything when time expires.
void Watchdog::Disarm() { void Watchdog::Disarm() {
if (NULL == handle_)
return;
AutoLock lock(lock_); AutoLock lock(lock_);
state_ = DISARMED; state_ = DISARMED;
// We don't need to signal, as the watchdog will eventually wake up, and it // We don't need to signal, as the watchdog will eventually wake up, and it
@ -86,43 +74,39 @@ void Watchdog::Disarm() {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Internal private methods that the watchdog thread uses. // Internal private methods that the watchdog thread uses.
// static void Watchdog::ThreadDelegate::ThreadMain() {
DWORD __stdcall Watchdog::ThreadStart(void* pThis) {
Watchdog* watchdog = reinterpret_cast<Watchdog*>(pThis);
return watchdog->Run();
}
unsigned Watchdog::Run() {
SetThreadName(); SetThreadName();
TimeDelta remaining_duration; TimeDelta remaining_duration;
while (1) { while (1) {
AutoLock lock(lock_); AutoLock lock(watchdog_->lock_);
while (DISARMED == state_) while (DISARMED == watchdog_->state_)
condition_variable_.Wait(); watchdog_->condition_variable_.Wait();
if (SHUTDOWN == state_) if (SHUTDOWN == watchdog_->state_)
return 0; return;
DCHECK(ARMED == state_); DCHECK(ARMED == watchdog_->state_);
remaining_duration = duration_ - (TimeTicks::Now() - start_time_); remaining_duration = duration_ -
(TimeTicks::Now() - watchdog_->start_time_);
if (remaining_duration.InMilliseconds() > 0) { if (remaining_duration.InMilliseconds() > 0) {
// Spurios wake? Timer drifts? Go back to sleep for remaining time. // Spurios wake? Timer drifts? Go back to sleep for remaining time.
condition_variable_.TimedWait(remaining_duration); watchdog_->condition_variable_.TimedWait(remaining_duration);
} else { } else {
// We overslept, so this seems like a real alarm. // We overslept, so this seems like a real alarm.
// Watch out for a user that stopped the debugger on a different alarm! // Watch out for a user that stopped the debugger on a different alarm!
{ {
AutoLock static_lock(static_lock_); AutoLock static_lock(static_lock_);
if (last_debugged_alarm_time_ > start_time_) { if (last_debugged_alarm_time_ > watchdog_->start_time_) {
// False alarm: we started our clock before the debugger break (last // False alarm: we started our clock before the debugger break (last
// alarm time). // alarm time).
start_time_ += last_debugged_alarm_delay_; watchdog_->start_time_ += last_debugged_alarm_delay_;
if (last_debugged_alarm_time_ > start_time_) if (last_debugged_alarm_time_ > watchdog_->start_time_)
state_ = DISARMED; // Too many alarms must have taken place. // Too many alarms must have taken place.
watchdog_->state_ = DISARMED;
continue; continue;
} }
} }
state_ = DISARMED; // Only alarm at most once. watchdog_->state_ = DISARMED; // Only alarm at most once.
TimeTicks last_alarm_time = TimeTicks::Now(); TimeTicks last_alarm_time = TimeTicks::Now();
Alarm(); // Set a break point here to debug on alarms. watchdog_->Alarm(); // Set a break point here to debug on alarms.
TimeDelta last_alarm_delay = TimeTicks::Now() - last_alarm_time; TimeDelta last_alarm_delay = TimeTicks::Now() - last_alarm_time;
if (last_alarm_delay > TimeDelta::FromMilliseconds(2)) { if (last_alarm_delay > TimeDelta::FromMilliseconds(2)) {
// Ignore race of two alarms/breaks going off at roughly the same time. // Ignore race of two alarms/breaks going off at roughly the same time.
@ -135,9 +119,8 @@ unsigned Watchdog::Run() {
} }
} }
void Watchdog::SetThreadName() const { void Watchdog::ThreadDelegate::SetThreadName() const {
std::string name = StringPrintf("%s Watchdog", std::string name = watchdog_->thread_watched_name_ + " Watchdog";
WideToASCII(thread_watched_name_).c_str());
PlatformThread::SetName(name.c_str()); PlatformThread::SetName(name.c_str());
DLOG(INFO) << "Watchdog active: " << name; DLOG(INFO) << "Watchdog active: " << name;
} }

@ -22,15 +22,15 @@
#include "base/condition_variable.h" #include "base/condition_variable.h"
#include "base/lock.h" #include "base/lock.h"
#include "base/platform_thread.h"
#include "base/time.h" #include "base/time.h"
class Watchdog { class Watchdog {
public: public:
// TODO(JAR)change default arg to required arg after all users have migrated.
// Constructor specifies how long the Watchdog will wait before alarming. // Constructor specifies how long the Watchdog will wait before alarming.
Watchdog(const base::TimeDelta& duration, Watchdog(const base::TimeDelta& duration,
const std::wstring& thread_watched_name, const std::string& thread_watched_name,
bool enabled = true); bool enabled);
virtual ~Watchdog(); virtual ~Watchdog();
// Start timing, and alarm when time expires (unless we're disarm()ed.) // Start timing, and alarm when time expires (unless we're disarm()ed.)
@ -48,22 +48,29 @@ class Watchdog {
} }
private: private:
class ThreadDelegate : public PlatformThread::Delegate {
public:
explicit ThreadDelegate(Watchdog* watchdog, const base::TimeDelta& duration)
: watchdog_(watchdog), duration_(duration) {
}
virtual void ThreadMain();
private:
Watchdog* watchdog_;
const base::TimeDelta duration_; // How long after start_time_ do we alarm?
void SetThreadName() const;
};
enum State {ARMED, DISARMED, SHUTDOWN }; enum State {ARMED, DISARMED, SHUTDOWN };
// Windows thread start callback bool init_successful_;
static DWORD WINAPI ThreadStart(void* pThis);
// Loop and test function for our watchdog thread.
unsigned Run();
void Watchdog::SetThreadName() const;
Lock lock_; // Mutex for state_. Lock lock_; // Mutex for state_.
ConditionVariable condition_variable_; ConditionVariable condition_variable_;
State state_; State state_;
const base::TimeDelta duration_; // How long after start_time_ do we alarm? const std::string thread_watched_name_;
const std::wstring thread_watched_name_; PlatformThreadHandle handle_;
HANDLE handle_; // Handle for watchdog thread. ThreadDelegate delegate_; // Store it, because it must outlive the thread.
DWORD thread_id_; // Also for watchdog thread.
base::TimeTicks start_time_; // Start of epoch, and alarm after duration_. base::TimeTicks start_time_; // Start of epoch, and alarm after duration_.
@ -79,8 +86,7 @@ class Watchdog {
// How long did we sit on a break in the debugger? // How long did we sit on a break in the debugger?
static base::TimeDelta last_debugged_alarm_delay_; static base::TimeDelta last_debugged_alarm_delay_;
DISALLOW_COPY_AND_ASSIGN(Watchdog);
DISALLOW_EVIL_CONSTRUCTORS(Watchdog);
}; };
#endif // BASE_WATCHDOG_H__ #endif // BASE_WATCHDOG_H__

@ -5,9 +5,10 @@
// Tests for Watchdog class. // Tests for Watchdog class.
#include "base/logging.h" #include "base/logging.h"
#include "base/watchdog.h" #include "base/platform_thread.h"
#include "base/spin_wait.h" #include "base/spin_wait.h"
#include "base/time.h" #include "base/time.h"
#include "base/watchdog.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
using base::TimeDelta; using base::TimeDelta;
@ -17,12 +18,11 @@ namespace {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Provide a derived class to facilitate testing. // Provide a derived class to facilitate testing.
// TODO(JAR): Remove default argument from constructor, and make mandatory.
class WatchdogCounter : public Watchdog { class WatchdogCounter : public Watchdog {
public: public:
WatchdogCounter(const TimeDelta& duration, WatchdogCounter(const TimeDelta& duration,
const std::wstring& thread_watched_name, const std::string& thread_watched_name,
bool enabled = true) bool enabled)
: Watchdog(duration, thread_watched_name, enabled), alarm_counter_(0) { : Watchdog(duration, thread_watched_name, enabled), alarm_counter_(0) {
} }
@ -38,7 +38,7 @@ class WatchdogCounter : public Watchdog {
private: private:
int alarm_counter_; int alarm_counter_;
DISALLOW_EVIL_CONSTRUCTORS(WatchdogCounter); DISALLOW_COPY_AND_ASSIGN(WatchdogCounter);
}; };
class WatchdogTest : public testing::Test { class WatchdogTest : public testing::Test {
@ -50,40 +50,28 @@ class WatchdogTest : public testing::Test {
// Minimal constructor/destructor test. // Minimal constructor/destructor test.
TEST(WatchdogTest, StartupShutdownTest) { TEST(WatchdogTest, StartupShutdownTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), L"Disabled", false); Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), L"Enabled", true); Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
// The following test is depricated, and should be removed when the
// default argument constructor is no longer accepted.
Watchdog watchdog3(TimeDelta::FromMilliseconds(300), L"Default");
} }
// Test ability to call Arm and Disarm repeatedly. // Test ability to call Arm and Disarm repeatedly.
TEST(WatchdogTest, ArmDisarmTest) { TEST(WatchdogTest, ArmDisarmTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), L"Disabled", false); Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
watchdog1.Arm(); watchdog1.Arm();
watchdog1.Disarm(); watchdog1.Disarm();
watchdog1.Arm(); watchdog1.Arm();
watchdog1.Disarm(); watchdog1.Disarm();
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), L"Enabled", true); Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
watchdog2.Arm(); watchdog2.Arm();
watchdog2.Disarm(); watchdog2.Disarm();
watchdog2.Arm(); watchdog2.Arm();
watchdog2.Disarm(); watchdog2.Disarm();
// The following test is depricated, and should be removed when the
// default argument constructor is no longer accepted.
Watchdog watchdog3(TimeDelta::FromMilliseconds(300), L"Default");
watchdog3.Arm();
watchdog3.Disarm();
watchdog3.Arm();
watchdog3.Disarm();
} }
// Make sure a basic alarm fires when the time has expired. // Make sure a basic alarm fires when the time has expired.
TEST(WatchdogTest, AlarmTest) { TEST(WatchdogTest, AlarmTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), L"Enabled", true); WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Enabled", true);
watchdog.Arm(); watchdog.Arm();
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromSeconds(1), SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromSeconds(1),
watchdog.alarm_counter() > 0); watchdog.alarm_counter() > 0);
@ -100,21 +88,21 @@ TEST(WatchdogTest, AlarmTest) {
// Make sure a disable alarm does nothing, even if we arm it. // Make sure a disable alarm does nothing, even if we arm it.
TEST(WatchdogTest, ConstructorDisabledTest) { TEST(WatchdogTest, ConstructorDisabledTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), L"Disabled", false); WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Disabled", false);
watchdog.Arm(); watchdog.Arm();
// Alarm should not fire, as it was disabled. // Alarm should not fire, as it was disabled.
Sleep(500); PlatformThread::Sleep(500);
EXPECT_EQ(0, watchdog.alarm_counter()); EXPECT_EQ(0, watchdog.alarm_counter());
} }
// Make sure Disarming will prevent firing, even after Arming. // Make sure Disarming will prevent firing, even after Arming.
TEST(WatchdogTest, DisarmTest) { TEST(WatchdogTest, DisarmTest) {
WatchdogCounter watchdog(TimeDelta::FromSeconds(1), L"Enabled", true); WatchdogCounter watchdog(TimeDelta::FromSeconds(1), "Enabled", true);
watchdog.Arm(); watchdog.Arm();
Sleep(100); // Don't sleep too long PlatformThread::Sleep(100); // Don't sleep too long
watchdog.Disarm(); watchdog.Disarm();
// Alarm should not fire. // Alarm should not fire.
Sleep(1500); PlatformThread::Sleep(1500);
EXPECT_EQ(0, watchdog.alarm_counter()); EXPECT_EQ(0, watchdog.alarm_counter());
// ...but even after disarming, we can still use the alarm... // ...but even after disarming, we can still use the alarm...

@ -54,7 +54,7 @@ class JankWatchdog : public Watchdog {
JankWatchdog(const TimeDelta& duration, JankWatchdog(const TimeDelta& duration,
const std::string& thread_watched_name, const std::string& thread_watched_name,
bool enabled) bool enabled)
: Watchdog(duration, ASCIIToWide(thread_watched_name), enabled), : Watchdog(duration, thread_watched_name, enabled),
thread_name_watched_(thread_watched_name), thread_name_watched_(thread_watched_name),
alarm_count_(0) { alarm_count_(0) {
} }
@ -72,7 +72,7 @@ class JankWatchdog : public Watchdog {
std::string thread_name_watched_; std::string thread_name_watched_;
int alarm_count_; int alarm_count_;
DISALLOW_EVIL_CONSTRUCTORS(JankWatchdog); DISALLOW_COPY_AND_ASSIGN(JankWatchdog);
}; };
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------