Fix random lint warnings in chrome/android/shell
[chromium-blink-merge.git] / chrome / browser / process_singleton_browsertest.cc
blob80957cd73088e46bd9262d818fc89302cedc8850
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This test validates that the ProcessSingleton class properly makes sure
6 // that there is only one main browser process.
7 //
8 // 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?)
13 #include "base/bind.h"
14 #include "base/command_line.h"
15 #include "base/files/file_path.h"
16 #include "base/files/scoped_temp_dir.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/path_service.h"
19 #include "base/process/kill.h"
20 #include "base/process/launch.h"
21 #include "base/process/process.h"
22 #include "base/process/process_iterator.h"
23 #include "base/synchronization/waitable_event.h"
24 #include "base/test/test_timeouts.h"
25 #include "base/threading/thread.h"
26 #include "chrome/common/chrome_constants.h"
27 #include "chrome/common/chrome_paths.h"
28 #include "chrome/common/chrome_switches.h"
29 #include "chrome/test/base/in_process_browser_test.h"
30 #include "chrome/test/base/test_launcher_utils.h"
32 namespace {
34 // This is for the code that is to be ran in multiple threads at once,
35 // to stress a race condition on first process start.
36 // We use the thread safe ref counted base class so that we can use the
37 // base::Bind to run the StartChrome methods in many threads.
38 class ChromeStarter : public base::RefCountedThreadSafe<ChromeStarter> {
39 public:
40 ChromeStarter(base::TimeDelta timeout, const base::FilePath& user_data_dir)
41 : ready_event_(false /* manual */, false /* signaled */),
42 done_event_(false /* manual */, false /* signaled */),
43 process_terminated_(false),
44 timeout_(timeout),
45 user_data_dir_(user_data_dir) {
48 // We must reset some data members since we reuse the same ChromeStarter
49 // object and start/stop it a few times. We must start fresh! :-)
50 void Reset() {
51 ready_event_.Reset();
52 done_event_.Reset();
53 if (process_.IsValid())
54 process_.Close();
55 process_terminated_ = false;
58 void StartChrome(base::WaitableEvent* start_event, bool first_run) {
59 // TODO(mattm): maybe stuff should be refactored to use
60 // UITest::LaunchBrowserHelper somehow?
61 base::FilePath program;
62 ASSERT_TRUE(PathService::Get(base::FILE_EXE, &program));
63 base::CommandLine command_line(program);
64 command_line.AppendSwitchPath(switches::kUserDataDir, user_data_dir_);
66 if (first_run)
67 command_line.AppendSwitch(switches::kForceFirstRun);
68 else
69 command_line.AppendSwitch(switches::kNoFirstRun);
71 // Add the normal test-mode switches, except for the ones we're adding
72 // ourselves.
73 base::CommandLine standard_switches(base::CommandLine::NO_PROGRAM);
74 test_launcher_utils::PrepareBrowserCommandLineForTests(&standard_switches);
75 const base::CommandLine::SwitchMap& switch_map =
76 standard_switches.GetSwitches();
77 for (base::CommandLine::SwitchMap::const_iterator i = switch_map.begin();
78 i != switch_map.end(); ++i) {
79 const std::string& switch_name = i->first;
80 if (switch_name == switches::kUserDataDir ||
81 switch_name == switches::kForceFirstRun ||
82 switch_name == switches::kNoFirstRun)
83 continue;
85 command_line.AppendSwitchNative(switch_name, i->second);
88 // Try to get all threads to launch the app at the same time.
89 // So let the test know we are ready.
90 ready_event_.Signal();
91 // And then wait for the test to tell us to GO!
92 ASSERT_NE(static_cast<base::WaitableEvent*>(NULL), start_event);
93 start_event->Wait();
95 // Here we don't wait for the app to be terminated because one of the
96 // process will stay alive while the others will be restarted. If we would
97 // wait here, we would never get a handle to the main process...
98 process_ = base::LaunchProcess(command_line, base::LaunchOptions());
99 ASSERT_TRUE(process_.IsValid());
101 // We can wait on the handle here, we should get stuck on one and only
102 // one process. The test below will take care of killing that process
103 // to unstuck us once it confirms there is only one.
104 process_terminated_ = base::WaitForSingleProcess(process_.Handle(),
105 timeout_);
106 // Let the test know we are done.
107 done_event_.Signal();
110 // Public access to simplify the test code using them.
111 base::WaitableEvent ready_event_;
112 base::WaitableEvent done_event_;
113 base::Process process_;
114 bool process_terminated_;
116 private:
117 friend class base::RefCountedThreadSafe<ChromeStarter>;
119 ~ChromeStarter() {}
121 base::TimeDelta timeout_;
122 base::FilePath user_data_dir_;
124 DISALLOW_COPY_AND_ASSIGN(ChromeStarter);
127 } // namespace
129 // Our test fixture that initializes and holds onto a few global vars.
130 class ProcessSingletonTest : public InProcessBrowserTest {
131 public:
132 ProcessSingletonTest()
133 // We use a manual reset so that all threads wake up at once when signaled
134 // and thus we must manually reset it for each attempt.
135 : threads_waker_(true /* manual */, false /* signaled */) {
136 EXPECT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
139 void SetUp() override {
140 // Start the threads and create the starters.
141 for (size_t i = 0; i < kNbThreads; ++i) {
142 chrome_starter_threads_[i].reset(new base::Thread("ChromeStarter"));
143 ASSERT_TRUE(chrome_starter_threads_[i]->Start());
144 chrome_starters_[i] = new ChromeStarter(
145 TestTimeouts::action_max_timeout(), temp_profile_dir_.path());
149 void TearDown() override {
150 // Stop the threads.
151 for (size_t i = 0; i < kNbThreads; ++i)
152 chrome_starter_threads_[i]->Stop();
155 // This method is used to make sure we kill the main browser process after
156 // all of its child processes have successfully attached to it. This was added
157 // when we realized that if we just kill the parent process right away, we
158 // sometimes end up with dangling child processes. If we Sleep for a certain
159 // amount of time, we are OK... So we introduced this method to avoid a
160 // flaky wait. Instead, we kill all descendants of the main process after we
161 // killed it, relying on the fact that we can still get the parent id of a
162 // child process, even when the parent dies.
163 void KillProcessTree(base::ProcessHandle process_handle) {
164 class ProcessTreeFilter : public base::ProcessFilter {
165 public:
166 explicit ProcessTreeFilter(base::ProcessId parent_pid) {
167 ancestor_pids_.insert(parent_pid);
169 bool Includes(const base::ProcessEntry& entry) const override {
170 if (ancestor_pids_.find(entry.parent_pid()) != ancestor_pids_.end()) {
171 ancestor_pids_.insert(entry.pid());
172 return true;
173 } else {
174 return false;
177 private:
178 mutable std::set<base::ProcessId> ancestor_pids_;
179 } process_tree_filter(base::GetProcId(process_handle));
181 // Start by explicitly killing the main process we know about...
182 static const int kExitCode = 42;
183 EXPECT_TRUE(base::KillProcess(process_handle, kExitCode, true /* wait */));
185 // Then loop until we can't find any of its descendant.
186 // But don't try more than kNbTries times...
187 static const int kNbTries = 10;
188 int num_tries = 0;
189 base::FilePath program;
190 ASSERT_TRUE(PathService::Get(base::FILE_EXE, &program));
191 base::FilePath::StringType exe_name = program.BaseName().value();
192 while (base::GetProcessCount(exe_name, &process_tree_filter) > 0 &&
193 num_tries++ < kNbTries) {
194 base::KillProcesses(exe_name, kExitCode, &process_tree_filter);
196 DLOG_IF(ERROR, num_tries >= kNbTries) << "Failed to kill all processes!";
199 // Since this is a hard to reproduce problem, we make a few attempts.
200 // We stop the attempts at the first error, and when there are no errors,
201 // we don't time-out of any wait, so it executes quite fast anyway.
202 static const size_t kNbAttempts = 5;
204 // The idea is to start chrome from multiple threads all at once.
205 static const size_t kNbThreads = 5;
206 scoped_refptr<ChromeStarter> chrome_starters_[kNbThreads];
207 scoped_ptr<base::Thread> chrome_starter_threads_[kNbThreads];
209 // The event that will get all threads to wake up simultaneously and try
210 // to start a chrome process at the same time.
211 base::WaitableEvent threads_waker_;
213 // We don't want to use the default profile, but can't use UITest's since we
214 // don't use UITest::LaunchBrowser.
215 base::ScopedTempDir temp_profile_dir_;
218 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
219 // http://crbug.com/58219
220 #define MAYBE_StartupRaceCondition DISABLED_StartupRaceCondition
221 #else
222 #define MAYBE_StartupRaceCondition StartupRaceCondition
223 #endif
224 IN_PROC_BROWSER_TEST_F(ProcessSingletonTest, MAYBE_StartupRaceCondition) {
225 // We use this to stop the attempts loop on the first failure.
226 bool failed = false;
227 for (size_t attempt = 0; attempt < kNbAttempts && !failed; ++attempt) {
228 SCOPED_TRACE(testing::Message() << "Attempt: " << attempt << ".");
229 // We use a single event to get all threads to do the AppLaunch at the same
230 // time...
231 threads_waker_.Reset();
233 // Test both with and without the first-run dialog, since they exercise
234 // different paths.
235 #if defined(OS_POSIX)
236 // TODO(mattm): test first run dialog singleton handling on linux too.
237 // On posix if we test the first run dialog, GracefulShutdownHandler gets
238 // the TERM signal, but since the message loop isn't running during the gtk
239 // first run dialog, the ShutdownDetector never handles it, and KillProcess
240 // has to time out (60 sec!) and SIGKILL.
241 bool first_run = false;
242 #else
243 // Test for races in both regular start up and first run start up cases.
244 bool first_run = attempt % 2;
245 #endif
247 // Here we prime all the threads with a ChromeStarter that will wait for
248 // our signal to launch its chrome process.
249 for (size_t i = 0; i < kNbThreads; ++i) {
250 ASSERT_NE(static_cast<ChromeStarter*>(NULL), chrome_starters_[i].get());
251 chrome_starters_[i]->Reset();
253 ASSERT_TRUE(chrome_starter_threads_[i]->IsRunning());
254 ASSERT_NE(static_cast<base::MessageLoop*>(NULL),
255 chrome_starter_threads_[i]->message_loop());
257 chrome_starter_threads_[i]->message_loop()->PostTask(
258 FROM_HERE, base::Bind(&ChromeStarter::StartChrome,
259 chrome_starters_[i].get(),
260 &threads_waker_,
261 first_run));
264 // Wait for all the starters to be ready.
265 // We could replace this loop if we ever implement a WaitAll().
266 for (size_t i = 0; i < kNbThreads; ++i) {
267 SCOPED_TRACE(testing::Message() << "Waiting on thread: " << i << ".");
268 chrome_starters_[i]->ready_event_.Wait();
270 // GO!
271 threads_waker_.Signal();
273 // As we wait for all threads to signal that they are done, we remove their
274 // index from this vector so that we get left with only the index of
275 // the thread that started the main process.
276 std::vector<size_t> pending_starters(kNbThreads);
277 for (size_t i = 0; i < kNbThreads; ++i)
278 pending_starters[i] = i;
280 // We use a local array of starter's done events we must wait on...
281 // These are collected from the starters that we have not yet been removed
282 // from the pending_starters vector.
283 base::WaitableEvent* starters_done_events[kNbThreads];
284 // At the end, "There can be only one" main browser process alive.
285 while (pending_starters.size() > 1) {
286 SCOPED_TRACE(testing::Message() << pending_starters.size() <<
287 " starters left.");
288 for (size_t i = 0; i < pending_starters.size(); ++i) {
289 starters_done_events[i] =
290 &chrome_starters_[pending_starters[i]]->done_event_;
292 size_t done_index = base::WaitableEvent::WaitMany(
293 starters_done_events, pending_starters.size());
294 size_t starter_index = pending_starters[done_index];
295 // If the starter is done but has not marked itself as terminated,
296 // it is because it timed out of its WaitForSingleProcess(). Only the
297 // last one standing should be left waiting... So we failed...
298 EXPECT_TRUE(chrome_starters_[starter_index]->process_terminated_ ||
299 failed) << "There is more than one main process.";
300 if (!chrome_starters_[starter_index]->process_terminated_) {
301 // This will stop the "for kNbAttempts" loop.
302 failed = true;
303 // But we let the last loop turn finish so that we can properly
304 // kill all remaining processes. Starting with this one...
305 if (chrome_starters_[starter_index]->process_.IsValid()) {
306 KillProcessTree(chrome_starters_[starter_index]->process_.Handle());
309 pending_starters.erase(pending_starters.begin() + done_index);
312 // "There can be only one!" :-)
313 ASSERT_EQ(static_cast<size_t>(1), pending_starters.size());
314 size_t last_index = pending_starters.front();
315 pending_starters.clear();
316 if (chrome_starters_[last_index]->process_.IsValid()) {
317 KillProcessTree(chrome_starters_[last_index]->process_.Handle());
318 chrome_starters_[last_index]->done_event_.Wait();