blob: 556a4bab3c5cf9aa680ce7c46c974598096bc029 [file] [log] [blame]
[email protected]697c7422012-04-11 16:27:011// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]bbef41f02010-03-04 16:16:192// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This test validates that the ProcessSingleton class properly makes sure
6// that there is only one main browser process.
7//
[email protected]bf4878d2010-06-16 20:12:018// It is currently compiled and run on Windows and Posix(non-Mac) platforms.
9// Mac uses system services and ProcessSingletonMac is a noop. (Maybe it still
10// makes sense to test that the system services are giving the behavior we
11// want?)
[email protected]bbef41f02010-03-04 16:16:1912
[email protected]0b05881d32011-11-17 00:44:0113#include "base/bind.h"
[email protected]77caa662012-04-23 15:40:4614#include "base/command_line.h"
[email protected]bbef41f02010-03-04 16:16:1915#include "base/file_path.h"
16#include "base/file_util.h"
[email protected]ea1a3f62012-11-16 20:34:2317#include "base/files/scoped_temp_dir.h"
[email protected]3b63f8f42011-03-28 01:54:1518#include "base/memory/ref_counted.h"
[email protected]bf4878d2010-06-16 20:12:0119#include "base/path_service.h"
[email protected]bbef41f02010-03-04 16:16:1920#include "base/process_util.h"
[email protected]44f9c952011-01-02 06:05:3921#include "base/synchronization/waitable_event.h"
[email protected]e0785902011-05-19 23:34:1722#include "base/test/test_timeouts.h"
23#include "base/threading/thread.h"
[email protected]bbef41f02010-03-04 16:16:1924#include "chrome/common/chrome_constants.h"
[email protected]e0785902011-05-19 23:34:1725#include "chrome/common/chrome_paths.h"
[email protected]bf4878d2010-06-16 20:12:0126#include "chrome/common/chrome_switches.h"
[email protected]77caa662012-04-23 15:40:4627#include "chrome/test/base/in_process_browser_test.h"
[email protected]ea1a3f62012-11-16 20:34:2328#include "chrome/test/base/test_launcher_utils.h"
[email protected]bbef41f02010-03-04 16:16:1929
30namespace {
31
32// This is for the code that is to be ran in multiple threads at once,
33// to stress a race condition on first process start.
34// We use the thread safe ref counted base class so that we can use the
[email protected]0b05881d32011-11-17 00:44:0135// base::Bind to run the StartChrome methods in many threads.
[email protected]bbef41f02010-03-04 16:16:1936class ChromeStarter : public base::RefCountedThreadSafe<ChromeStarter> {
37 public:
[email protected]8270c6fe2012-07-09 19:59:2138 ChromeStarter(base::TimeDelta timeout, const FilePath& user_data_dir)
[email protected]bbef41f02010-03-04 16:16:1939 : ready_event_(false /* manual */, false /* signaled */),
40 done_event_(false /* manual */, false /* signaled */),
[email protected]8b8fab972011-01-13 16:27:1841 process_handle_(base::kNullProcessHandle),
[email protected]0e60b642010-03-30 10:21:2742 process_terminated_(false),
[email protected]8270c6fe2012-07-09 19:59:2143 timeout_(timeout),
[email protected]1a30a2f32010-10-06 02:03:0444 user_data_dir_(user_data_dir) {
[email protected]bbef41f02010-03-04 16:16:1945 }
46
47 // We must reset some data members since we reuse the same ChromeStarter
48 // object and start/stop it a few times. We must start fresh! :-)
49 void Reset() {
50 ready_event_.Reset();
51 done_event_.Reset();
[email protected]bf4878d2010-06-16 20:12:0152 if (process_handle_ != base::kNullProcessHandle)
[email protected]bbef41f02010-03-04 16:16:1953 base::CloseProcessHandle(process_handle_);
[email protected]bf4878d2010-06-16 20:12:0154 process_handle_ = base::kNullProcessHandle;
[email protected]bbef41f02010-03-04 16:16:1955 process_terminated_ = false;
56 }
57
[email protected]bf4878d2010-06-16 20:12:0158 void StartChrome(base::WaitableEvent* start_event, bool first_run) {
59 // TODO(mattm): maybe stuff should be refactored to use
60 // UITest::LaunchBrowserHelper somehow?
[email protected]77caa662012-04-23 15:40:4661 FilePath program;
62 ASSERT_TRUE(PathService::Get(base::FILE_EXE, &program));
63 CommandLine command_line(program);
[email protected]1a30a2f32010-10-06 02:03:0464 command_line.AppendSwitchPath(switches::kUserDataDir, user_data_dir_);
[email protected]bf4878d2010-06-16 20:12:0165
66 if (first_run)
[email protected]3f002a32013-01-02 17:52:3867 command_line.AppendSwitch(switches::kForceFirstRun);
[email protected]bf4878d2010-06-16 20:12:0168 else
69 command_line.AppendSwitch(switches::kNoFirstRun);
[email protected]bbef41f02010-03-04 16:16:1970
[email protected]1a30a2f32010-10-06 02:03:0471 // Add the normal test-mode switches, except for the ones we're adding
72 // ourselves.
[email protected]947446b2010-10-21 03:36:3173 CommandLine standard_switches(CommandLine::NO_PROGRAM);
[email protected]1a30a2f32010-10-06 02:03:0474 test_launcher_utils::PrepareBrowserCommandLineForTests(&standard_switches);
75 const CommandLine::SwitchMap& switch_map = standard_switches.GetSwitches();
76 for (CommandLine::SwitchMap::const_iterator i = switch_map.begin();
77 i != switch_map.end(); ++i) {
78 const std::string& switch_name = i->first;
79 if (switch_name == switches::kUserDataDir ||
[email protected]3f002a32013-01-02 17:52:3880 switch_name == switches::kForceFirstRun ||
[email protected]1a30a2f32010-10-06 02:03:0481 switch_name == switches::kNoFirstRun)
82 continue;
83
84 command_line.AppendSwitchNative(switch_name, i->second);
85 }
86
[email protected]bbef41f02010-03-04 16:16:1987 // Try to get all threads to launch the app at the same time.
88 // So let the test know we are ready.
89 ready_event_.Signal();
90 // And then wait for the test to tell us to GO!
91 ASSERT_NE(static_cast<base::WaitableEvent*>(NULL), start_event);
[email protected]866cf332011-10-12 03:09:4292 start_event->Wait();
[email protected]bbef41f02010-03-04 16:16:1993
94 // Here we don't wait for the app to be terminated because one of the
95 // process will stay alive while the others will be restarted. If we would
96 // wait here, we would never get a handle to the main process...
[email protected]e5992182011-07-15 16:47:0297 base::LaunchProcess(command_line, base::LaunchOptions(), &process_handle_);
[email protected]bf4878d2010-06-16 20:12:0198 ASSERT_NE(base::kNullProcessHandle, process_handle_);
[email protected]bbef41f02010-03-04 16:16:1999
100 // We can wait on the handle here, we should get stuck on one and only
101 // one process. The test below will take care of killing that process
102 // to unstuck us once it confirms there is only one.
[email protected]bbef41f02010-03-04 16:16:19103 process_terminated_ = base::WaitForSingleProcess(process_handle_,
[email protected]8270c6fe2012-07-09 19:59:21104 timeout_);
[email protected]bbef41f02010-03-04 16:16:19105 // Let the test know we are done.
106 done_event_.Signal();
107 }
108
109 // Public access to simplify the test code using them.
110 base::WaitableEvent ready_event_;
111 base::WaitableEvent done_event_;
112 base::ProcessHandle process_handle_;
113 bool process_terminated_;
114
115 private:
116 friend class base::RefCountedThreadSafe<ChromeStarter>;
[email protected]0e60b642010-03-30 10:21:27117
[email protected]bbef41f02010-03-04 16:16:19118 ~ChromeStarter() {
[email protected]bf4878d2010-06-16 20:12:01119 if (process_handle_ != base::kNullProcessHandle)
[email protected]bbef41f02010-03-04 16:16:19120 base::CloseProcessHandle(process_handle_);
121 }
[email protected]0e60b642010-03-30 10:21:27122
[email protected]8270c6fe2012-07-09 19:59:21123 base::TimeDelta timeout_;
[email protected]1a30a2f32010-10-06 02:03:04124 FilePath user_data_dir_;
[email protected]0e60b642010-03-30 10:21:27125
[email protected]bbef41f02010-03-04 16:16:19126 DISALLOW_COPY_AND_ASSIGN(ChromeStarter);
127};
128
[email protected]77caa662012-04-23 15:40:46129} // namespace
130
[email protected]bbef41f02010-03-04 16:16:19131// Our test fixture that initializes and holds onto a few global vars.
[email protected]77caa662012-04-23 15:40:46132class ProcessSingletonTest : public InProcessBrowserTest {
[email protected]bbef41f02010-03-04 16:16:19133 public:
[email protected]bf4878d2010-06-16 20:12:01134 ProcessSingletonTest()
[email protected]bbef41f02010-03-04 16:16:19135 // We use a manual reset so that all threads wake up at once when signaled
136 // and thus we must manually reset it for each attempt.
137 : threads_waker_(true /* manual */, false /* signaled */) {
[email protected]2d57f5d2011-01-13 14:20:12138 EXPECT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
[email protected]bbef41f02010-03-04 16:16:19139 }
140
141 void SetUp() {
142 // Start the threads and create the starters.
143 for (size_t i = 0; i < kNbThreads; ++i) {
144 chrome_starter_threads_[i].reset(new base::Thread("ChromeStarter"));
145 ASSERT_TRUE(chrome_starter_threads_[i]->Start());
[email protected]d64295932011-01-19 22:37:31146 chrome_starters_[i] = new ChromeStarter(
[email protected]8270c6fe2012-07-09 19:59:21147 TestTimeouts::action_max_timeout(), temp_profile_dir_.path());
[email protected]bbef41f02010-03-04 16:16:19148 }
149 }
150
151 void TearDown() {
152 // Stop the threads.
153 for (size_t i = 0; i < kNbThreads; ++i)
154 chrome_starter_threads_[i]->Stop();
155 }
156
157 // This method is used to make sure we kill the main browser process after
158 // all of its child processes have successfully attached to it. This was added
159 // when we realized that if we just kill the parent process right away, we
160 // sometimes end up with dangling child processes. If we Sleep for a certain
161 // amount of time, we are OK... So we introduced this method to avoid a
162 // flaky wait. Instead, we kill all descendants of the main process after we
163 // killed it, relying on the fact that we can still get the parent id of a
164 // child process, even when the parent dies.
165 void KillProcessTree(base::ProcessHandle process_handle) {
166 class ProcessTreeFilter : public base::ProcessFilter {
167 public:
168 explicit ProcessTreeFilter(base::ProcessId parent_pid) {
169 ancestor_pids_.insert(parent_pid);
170 }
[email protected]b6128aa2010-04-29 17:44:42171 virtual bool Includes(const base::ProcessEntry & entry) const {
172 if (ancestor_pids_.find(entry.parent_pid()) != ancestor_pids_.end()) {
173 ancestor_pids_.insert(entry.pid());
[email protected]bbef41f02010-03-04 16:16:19174 return true;
175 } else {
176 return false;
177 }
178 }
179 private:
180 mutable std::set<base::ProcessId> ancestor_pids_;
181 } process_tree_filter(base::GetProcId(process_handle));
182
183 // Start by explicitly killing the main process we know about...
184 static const int kExitCode = 42;
185 EXPECT_TRUE(base::KillProcess(process_handle, kExitCode, true /* wait */));
186
187 // Then loop until we can't find any of its descendant.
188 // But don't try more than kNbTries times...
189 static const int kNbTries = 10;
190 int num_tries = 0;
[email protected]77caa662012-04-23 15:40:46191 FilePath program;
192 ASSERT_TRUE(PathService::Get(base::FILE_EXE, &program));
193 FilePath::StringType exe_name = program.BaseName().value();
194 while (base::GetProcessCount(exe_name, &process_tree_filter) > 0 &&
195 num_tries++ < kNbTries) {
196 base::KillProcesses(exe_name, kExitCode, &process_tree_filter);
[email protected]bbef41f02010-03-04 16:16:19197 }
198 DLOG_IF(ERROR, num_tries >= kNbTries) << "Failed to kill all processes!";
199 }
200
201 // Since this is a hard to reproduce problem, we make a few attempts.
202 // We stop the attempts at the first error, and when there are no errors,
203 // we don't time-out of any wait, so it executes quite fast anyway.
204 static const size_t kNbAttempts = 5;
205
206 // The idea is to start chrome from multiple threads all at once.
207 static const size_t kNbThreads = 5;
208 scoped_refptr<ChromeStarter> chrome_starters_[kNbThreads];
209 scoped_ptr<base::Thread> chrome_starter_threads_[kNbThreads];
210
211 // The event that will get all threads to wake up simultaneously and try
212 // to start a chrome process at the same time.
213 base::WaitableEvent threads_waker_;
[email protected]1a30a2f32010-10-06 02:03:04214
215 // We don't want to use the default profile, but can't use UITest's since we
216 // don't use UITest::LaunchBrowser.
[email protected]ea1a3f62012-11-16 20:34:23217 base::ScopedTempDir temp_profile_dir_;
[email protected]bbef41f02010-03-04 16:16:19218};
219
[email protected]b03a1382010-10-06 23:52:05220#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
221// http://crbug.com/58219
[email protected]e00ccc92012-11-01 17:32:30222#define MAYBE_StartupRaceCondition DISABLED_StartupRaceCondition
[email protected]b03a1382010-10-06 23:52:05223#else
224#define MAYBE_StartupRaceCondition StartupRaceCondition
225#endif
[email protected]77caa662012-04-23 15:40:46226IN_PROC_BROWSER_TEST_F(ProcessSingletonTest, MAYBE_StartupRaceCondition) {
[email protected]bbef41f02010-03-04 16:16:19227 // We use this to stop the attempts loop on the first failure.
228 bool failed = false;
229 for (size_t attempt = 0; attempt < kNbAttempts && !failed; ++attempt) {
230 SCOPED_TRACE(testing::Message() << "Attempt: " << attempt << ".");
231 // We use a single event to get all threads to do the AppLaunch at the same
232 // time...
233 threads_waker_.Reset();
234
[email protected]bf4878d2010-06-16 20:12:01235 // Test both with and without the first-run dialog, since they exercise
236 // different paths.
237#if defined(OS_POSIX)
238 // TODO(mattm): test first run dialog singleton handling on linux too.
239 // On posix if we test the first run dialog, GracefulShutdownHandler gets
240 // the TERM signal, but since the message loop isn't running during the gtk
241 // first run dialog, the ShutdownDetector never handles it, and KillProcess
242 // has to time out (60 sec!) and SIGKILL.
243 bool first_run = false;
244#else
245 // Test for races in both regular start up and first run start up cases.
246 bool first_run = attempt % 2;
247#endif
248
[email protected]bbef41f02010-03-04 16:16:19249 // Here we prime all the threads with a ChromeStarter that will wait for
250 // our signal to launch its chrome process.
251 for (size_t i = 0; i < kNbThreads; ++i) {
252 ASSERT_NE(static_cast<ChromeStarter*>(NULL), chrome_starters_[i].get());
253 chrome_starters_[i]->Reset();
254
255 ASSERT_TRUE(chrome_starter_threads_[i]->IsRunning());
256 ASSERT_NE(static_cast<MessageLoop*>(NULL),
257 chrome_starter_threads_[i]->message_loop());
258
259 chrome_starter_threads_[i]->message_loop()->PostTask(
[email protected]0b05881d32011-11-17 00:44:01260 FROM_HERE, base::Bind(&ChromeStarter::StartChrome,
261 chrome_starters_[i].get(),
262 &threads_waker_,
263 first_run));
[email protected]bbef41f02010-03-04 16:16:19264 }
265
266 // Wait for all the starters to be ready.
267 // We could replace this loop if we ever implement a WaitAll().
268 for (size_t i = 0; i < kNbThreads; ++i) {
269 SCOPED_TRACE(testing::Message() << "Waiting on thread: " << i << ".");
[email protected]866cf332011-10-12 03:09:42270 chrome_starters_[i]->ready_event_.Wait();
[email protected]bbef41f02010-03-04 16:16:19271 }
272 // GO!
273 threads_waker_.Signal();
274
275 // As we wait for all threads to signal that they are done, we remove their
276 // index from this vector so that we get left with only the index of
277 // the thread that started the main process.
278 std::vector<size_t> pending_starters(kNbThreads);
279 for (size_t i = 0; i < kNbThreads; ++i)
280 pending_starters[i] = i;
281
282 // We use a local array of starter's done events we must wait on...
283 // These are collected from the starters that we have not yet been removed
284 // from the pending_starters vector.
285 base::WaitableEvent* starters_done_events[kNbThreads];
286 // At the end, "There can be only one" main browser process alive.
287 while (pending_starters.size() > 1) {
288 SCOPED_TRACE(testing::Message() << pending_starters.size() <<
289 " starters left.");
290 for (size_t i = 0; i < pending_starters.size(); ++i) {
291 starters_done_events[i] =
292 &chrome_starters_[pending_starters[i]]->done_event_;
293 }
294 size_t done_index = base::WaitableEvent::WaitMany(
295 starters_done_events, pending_starters.size());
296 size_t starter_index = pending_starters[done_index];
297 // If the starter is done but has not marked itself as terminated,
298 // it is because it timed out of its WaitForSingleProcess(). Only the
299 // last one standing should be left waiting... So we failed...
300 EXPECT_TRUE(chrome_starters_[starter_index]->process_terminated_ ||
301 failed) << "There is more than one main process.";
302 if (!chrome_starters_[starter_index]->process_terminated_) {
303 // This will stop the "for kNbAttempts" loop.
304 failed = true;
305 // But we let the last loop turn finish so that we can properly
306 // kill all remaining processes. Starting with this one...
[email protected]bf4878d2010-06-16 20:12:01307 if (chrome_starters_[starter_index]->process_handle_ !=
308 base::kNullProcessHandle) {
[email protected]bbef41f02010-03-04 16:16:19309 KillProcessTree(chrome_starters_[starter_index]->process_handle_);
310 }
311 }
312 pending_starters.erase(pending_starters.begin() + done_index);
313 }
314
315 // "There can be only one!" :-)
316 ASSERT_EQ(static_cast<size_t>(1), pending_starters.size());
317 size_t last_index = pending_starters.front();
[email protected]697c7422012-04-11 16:27:01318 pending_starters.clear();
[email protected]bf4878d2010-06-16 20:12:01319 if (chrome_starters_[last_index]->process_handle_ !=
320 base::kNullProcessHandle) {
[email protected]bbef41f02010-03-04 16:16:19321 KillProcessTree(chrome_starters_[last_index]->process_handle_);
322 chrome_starters_[last_index]->done_event_.Wait();
323 }
324 }
325}