process_singleton_browsertest.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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.
  4. // This test validates that the ProcessSingleton class properly makes sure
  5. // that there is only one main browser process.
  6. //
  7. // It is currently compiled and run on Windows and Posix(non-Mac) platforms.
  8. // Mac uses system services and ProcessSingletonMac is a noop. (Maybe it still
  9. // makes sense to test that the system services are giving the behavior we
  10. // want?)
  11. #include <stddef.h>
  12. #include <memory>
  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/location.h"
  18. #include "base/memory/ref_counted.h"
  19. #include "base/path_service.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/task/single_thread_task_runner.h"
  25. #include "base/test/test_timeouts.h"
  26. #include "base/threading/thread.h"
  27. #include "base/time/time.h"
  28. #include "build/build_config.h"
  29. #include "chrome/common/chrome_constants.h"
  30. #include "chrome/common/chrome_paths.h"
  31. #include "chrome/common/chrome_result_codes.h"
  32. #include "chrome/common/chrome_switches.h"
  33. #include "chrome/test/base/in_process_browser_test.h"
  34. #include "chrome/test/base/test_launcher_utils.h"
  35. #include "content/public/test/browser_test.h"
  36. #include "testing/gmock/include/gmock/gmock.h"
  37. using ::testing::AnyOf;
  38. using ::testing::Eq;
  39. namespace {
  40. // This is for the code that is to be ran in multiple threads at once,
  41. // to stress a race condition on first process start.
  42. // We use the thread safe ref counted base class so that we can use the
  43. // base::Bind to run the StartChrome methods in many threads.
  44. class ChromeStarter : public base::RefCountedThreadSafe<ChromeStarter> {
  45. public:
  46. ChromeStarter(base::TimeDelta timeout,
  47. const base::FilePath& user_data_dir,
  48. const base::CommandLine& initial_command_line_for_relaunch)
  49. : ready_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
  50. base::WaitableEvent::InitialState::NOT_SIGNALED),
  51. done_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
  52. base::WaitableEvent::InitialState::NOT_SIGNALED),
  53. process_terminated_(false),
  54. timeout_(timeout),
  55. user_data_dir_(user_data_dir),
  56. initial_command_line_for_relaunch_(initial_command_line_for_relaunch) {}
  57. ChromeStarter(const ChromeStarter&) = delete;
  58. ChromeStarter& operator=(const ChromeStarter&) = delete;
  59. // We must reset some data members since we reuse the same ChromeStarter
  60. // object and start/stop it a few times. We must start fresh! :-)
  61. void Reset() {
  62. ready_event_.Reset();
  63. done_event_.Reset();
  64. if (process_.IsValid())
  65. process_.Close();
  66. process_terminated_ = false;
  67. }
  68. void StartChrome(base::WaitableEvent* start_event, bool first_run) {
  69. base::CommandLine command_line_for_relaunch(
  70. initial_command_line_for_relaunch_.GetProgram());
  71. test_launcher_utils::RemoveCommandLineSwitch(
  72. initial_command_line_for_relaunch_, switches::kUserDataDir,
  73. &command_line_for_relaunch);
  74. command_line_for_relaunch.AppendSwitchPath(switches::kUserDataDir,
  75. user_data_dir_);
  76. if (first_run) {
  77. base::CommandLine tmp_command_line = command_line_for_relaunch;
  78. test_launcher_utils::RemoveCommandLineSwitch(
  79. tmp_command_line, switches::kNoFirstRun, &command_line_for_relaunch);
  80. command_line_for_relaunch.AppendSwitch(switches::kForceFirstRun);
  81. }
  82. // Try to get all threads to launch the app at the same time.
  83. // So let the test know we are ready.
  84. ready_event_.Signal();
  85. // And then wait for the test to tell us to GO!
  86. ASSERT_NE(nullptr, start_event);
  87. start_event->Wait();
  88. // Here we don't wait for the app to be terminated because one of the
  89. // process will stay alive while the others will be restarted. If we would
  90. // wait here, we would never get a handle to the main process...
  91. process_ =
  92. base::LaunchProcess(command_line_for_relaunch, base::LaunchOptions());
  93. ASSERT_TRUE(process_.IsValid());
  94. // We can wait on the handle here, we should get stuck on one and only
  95. // one process. The test below will take care of killing that process
  96. // to unstuck us once it confirms there is only one.
  97. process_terminated_ =
  98. process_.WaitForExitWithTimeout(timeout_, &exit_code_);
  99. // Let the test know we are done.
  100. done_event_.Signal();
  101. }
  102. // Public access to simplify the test code using them.
  103. base::WaitableEvent ready_event_;
  104. base::WaitableEvent done_event_;
  105. base::Process process_;
  106. bool process_terminated_;
  107. // Process exit code. Only meaningful if |process_terminated_| is true.
  108. int exit_code_;
  109. private:
  110. friend class base::RefCountedThreadSafe<ChromeStarter>;
  111. ~ChromeStarter() {}
  112. base::TimeDelta timeout_;
  113. base::FilePath user_data_dir_;
  114. base::CommandLine initial_command_line_for_relaunch_;
  115. };
  116. } // namespace
  117. // Our test fixture that initializes and holds onto a few global vars.
  118. class ProcessSingletonTest : public InProcessBrowserTest {
  119. public:
  120. ProcessSingletonTest()
  121. // We use a manual reset so that all threads wake up at once when signaled
  122. // and thus we must manually reset it for each attempt.
  123. : threads_waker_(base::WaitableEvent::ResetPolicy::MANUAL,
  124. base::WaitableEvent::InitialState::NOT_SIGNALED) {
  125. EXPECT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
  126. }
  127. void TearDown() override {
  128. InProcessBrowserTest::TearDown();
  129. // Stop the threads.
  130. for (size_t i = 0; i < kNbThreads; ++i)
  131. chrome_starter_threads_[i]->Stop();
  132. }
  133. // This method is used to make sure we kill the main browser process after
  134. // all of its child processes have successfully attached to it. This was added
  135. // when we realized that if we just kill the parent process right away, we
  136. // sometimes end up with dangling child processes. If we Sleep for a certain
  137. // amount of time, we are OK... So we introduced this method to avoid a
  138. // flaky wait. Instead, we kill all descendants of the main process after we
  139. // killed it, relying on the fact that we can still get the parent id of a
  140. // child process, even when the parent dies.
  141. void KillProcessTree(const base::Process& process) {
  142. class ProcessTreeFilter : public base::ProcessFilter {
  143. public:
  144. explicit ProcessTreeFilter(base::ProcessId parent_pid) {
  145. ancestor_pids_.insert(parent_pid);
  146. }
  147. bool Includes(const base::ProcessEntry& entry) const override {
  148. if (ancestor_pids_.find(entry.parent_pid()) != ancestor_pids_.end()) {
  149. ancestor_pids_.insert(entry.pid());
  150. return true;
  151. } else {
  152. return false;
  153. }
  154. }
  155. private:
  156. mutable std::set<base::ProcessId> ancestor_pids_;
  157. } process_tree_filter(process.Pid());
  158. // Start by explicitly killing the main process we know about...
  159. static const int kExitCode = 42;
  160. EXPECT_TRUE(process.Terminate(kExitCode, true /* wait */));
  161. // Then loop until we can't find any of its descendant.
  162. // But don't try more than kNbTries times...
  163. static const int kNbTries = 10;
  164. int num_tries = 0;
  165. base::FilePath program;
  166. ASSERT_TRUE(base::PathService::Get(base::FILE_EXE, &program));
  167. base::FilePath::StringType exe_name = program.BaseName().value();
  168. while (base::GetProcessCount(exe_name, &process_tree_filter) > 0 &&
  169. num_tries++ < kNbTries) {
  170. base::KillProcesses(exe_name, kExitCode, &process_tree_filter);
  171. }
  172. DLOG_IF(ERROR, num_tries >= kNbTries) << "Failed to kill all processes!";
  173. }
  174. // Since this is a hard to reproduce problem, we make a few attempts.
  175. // We stop the attempts at the first error, and when there are no errors,
  176. // we don't time-out of any wait, so it executes quite fast anyway.
  177. static const size_t kNbAttempts = 5;
  178. // The idea is to start chrome from multiple threads all at once.
  179. static const size_t kNbThreads = 5;
  180. scoped_refptr<ChromeStarter> chrome_starters_[kNbThreads];
  181. std::unique_ptr<base::Thread> chrome_starter_threads_[kNbThreads];
  182. // The event that will get all threads to wake up simultaneously and try
  183. // to start a chrome process at the same time.
  184. base::WaitableEvent threads_waker_;
  185. // We don't want to use the default profile, but can't use UITest's since we
  186. // don't use UITest::LaunchBrowser.
  187. base::ScopedTempDir temp_profile_dir_;
  188. };
  189. // ChromeOS hits DCHECKS on ProcessSingleton rendezvous: crbug.com/782487
  190. #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
  191. #define MAYBE_StartupRaceCondition DISABLED_StartupRaceCondition
  192. #else
  193. #define MAYBE_StartupRaceCondition StartupRaceCondition
  194. #endif
  195. IN_PROC_BROWSER_TEST_F(ProcessSingletonTest, MAYBE_StartupRaceCondition) {
  196. // Start the threads and create the starters.
  197. for (size_t i = 0; i < kNbThreads; ++i) {
  198. chrome_starter_threads_[i] =
  199. std::make_unique<base::Thread>("ChromeStarter");
  200. ASSERT_TRUE(chrome_starter_threads_[i]->Start());
  201. chrome_starters_[i] = base::MakeRefCounted<ChromeStarter>(
  202. TestTimeouts::action_max_timeout(), temp_profile_dir_.GetPath(),
  203. GetCommandLineForRelaunch());
  204. }
  205. for (size_t attempt = 0; attempt < kNbAttempts && !HasFailure(); ++attempt) {
  206. SCOPED_TRACE(testing::Message() << "Attempt: " << attempt << ".");
  207. // We use a single event to get all threads to do the AppLaunch at the
  208. // same time...
  209. threads_waker_.Reset();
  210. // Test both with and without the first-run dialog, since they exercise
  211. // different paths.
  212. #if BUILDFLAG(IS_POSIX)
  213. // TODO(mattm): test first run dialog singleton handling on linux too.
  214. // On posix if we test the first run dialog, GracefulShutdownHandler gets
  215. // the TERM signal, but since the message loop isn't running during the gtk
  216. // first run dialog, the ShutdownDetector never handles it, and KillProcess
  217. // has to time out (60 sec!) and SIGKILL.
  218. bool first_run = false;
  219. #else
  220. // Test for races in both regular start up and first run start up cases.
  221. bool first_run = attempt % 2;
  222. #endif
  223. // Here we prime all the threads with a ChromeStarter that will wait for
  224. // our signal to launch its chrome process.
  225. for (size_t i = 0; i < kNbThreads; ++i) {
  226. ASSERT_NE(static_cast<ChromeStarter*>(NULL), chrome_starters_[i].get());
  227. chrome_starters_[i]->Reset();
  228. ASSERT_TRUE(chrome_starter_threads_[i]->IsRunning());
  229. ASSERT_TRUE(chrome_starter_threads_[i]->task_runner());
  230. chrome_starter_threads_[i]->task_runner()->PostTask(
  231. FROM_HERE,
  232. base::BindOnce(&ChromeStarter::StartChrome, chrome_starters_[i],
  233. &threads_waker_, first_run));
  234. }
  235. // Wait for all the starters to be ready.
  236. // We could replace this loop if we ever implement a WaitAll().
  237. for (size_t i = 0; i < kNbThreads; ++i) {
  238. SCOPED_TRACE(testing::Message() << "Waiting on thread: " << i << ".");
  239. chrome_starters_[i]->ready_event_.Wait();
  240. }
  241. // GO!
  242. threads_waker_.Signal();
  243. // As we wait for all threads to signal that they are done, we remove their
  244. // index from this vector so that we get left with only the index of
  245. // the thread that started the main process.
  246. std::vector<size_t> pending_starters(kNbThreads);
  247. for (size_t i = 0; i < kNbThreads; ++i)
  248. pending_starters[i] = i;
  249. // We use a local array of starter's done events we must wait on...
  250. // These are collected from the starters that we have not yet been removed
  251. // from the pending_starters vector.
  252. base::WaitableEvent* starters_done_events[kNbThreads];
  253. // At the end, "There can be only one" main browser process alive.
  254. while (pending_starters.size() > 1) {
  255. SCOPED_TRACE(testing::Message() << pending_starters.size() <<
  256. " starters left.");
  257. for (size_t i = 0; i < pending_starters.size(); ++i) {
  258. starters_done_events[i] =
  259. &chrome_starters_[pending_starters[i]]->done_event_;
  260. }
  261. size_t done_index = base::WaitableEvent::WaitMany(
  262. starters_done_events, pending_starters.size());
  263. size_t starter_index = pending_starters[done_index];
  264. // If the starter is done but has not marked itself as terminated,
  265. // it is because it timed out of its WaitForExitCodeWithTimeout(). Only
  266. // the last one standing should be left waiting... So we failed...
  267. EXPECT_TRUE(chrome_starters_[starter_index]->process_terminated_)
  268. << "There is more than one main process.";
  269. if (chrome_starters_[starter_index]->process_terminated_) {
  270. // Generally PROCESS_NOTIFIED would be the expected exit code. In some
  271. // rare cases the ProcessSingleton race can result in PROFILE_IN_USE
  272. // exit code, which we also allow, though it would be ideal if that
  273. // never happened.
  274. // TODO(mattm): investigate why PROFILE_IN_USE occurs sometimes.
  275. EXPECT_THAT(
  276. chrome_starters_[starter_index]->exit_code_,
  277. AnyOf(Eq(chrome::RESULT_CODE_PROFILE_IN_USE),
  278. Eq(chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED)));
  279. } else {
  280. // But we let the last loop turn finish so that we can properly
  281. // kill all remaining processes. Starting with this one...
  282. if (chrome_starters_[starter_index]->process_.IsValid()) {
  283. KillProcessTree(chrome_starters_[starter_index]->process_);
  284. }
  285. }
  286. pending_starters.erase(pending_starters.begin() + done_index);
  287. }
  288. // "There can be only one!" :-)
  289. ASSERT_EQ(static_cast<size_t>(1), pending_starters.size());
  290. size_t last_index = pending_starters.front();
  291. pending_starters.clear();
  292. if (chrome_starters_[last_index]->process_.IsValid()) {
  293. KillProcessTree(chrome_starters_[last_index]->process_);
  294. chrome_starters_[last_index]->done_event_.Wait();
  295. }
  296. }
  297. }