system_perfetto_unittest.cc 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. // Copyright 2019 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. #include <cerrno>
  5. #include <cstdlib>
  6. #include <memory>
  7. #include <string>
  8. #include <thread>
  9. #include <utility>
  10. #include "base/bind.h"
  11. #include "base/callback.h"
  12. #include "base/files/file_util.h"
  13. #include "base/files/scoped_temp_dir.h"
  14. #include "base/process/launch.h"
  15. #include "base/rand_util.h"
  16. #include "base/run_loop.h"
  17. #include "base/strings/strcat.h"
  18. #include "base/strings/string_number_conversions.h"
  19. #include "base/test/bind.h"
  20. #include "base/test/scoped_feature_list.h"
  21. #include "base/trace_event/trace_config.h"
  22. #include "build/build_config.h"
  23. #include "build/chromeos_buildflags.h"
  24. #include "services/tracing/perfetto/perfetto_service.h"
  25. #include "services/tracing/perfetto/producer_host.h"
  26. #include "services/tracing/perfetto/system_test_utils.h"
  27. #include "services/tracing/perfetto/test_utils.h"
  28. #include "services/tracing/public/cpp/perfetto/dummy_producer.h"
  29. #include "services/tracing/public/cpp/perfetto/producer_client.h"
  30. #include "services/tracing/public/cpp/system_tracing_service.h"
  31. #include "services/tracing/public/cpp/trace_startup.h"
  32. #include "services/tracing/public/cpp/traced_process_impl.h"
  33. #include "services/tracing/public/cpp/tracing_features.h"
  34. #include "testing/gtest/include/gtest/gtest-death-test.h"
  35. #include "testing/gtest/include/gtest/gtest.h"
  36. #include "third_party/perfetto/include/perfetto/ext/tracing/ipc/default_socket.h"
  37. #include "third_party/perfetto/protos/perfetto/config/trace_config.pb.h"
  38. #include "third_party/perfetto/protos/perfetto/trace/trace.pb.h"
  39. #if BUILDFLAG(IS_ANDROID)
  40. #include "base/android/build_info.h" // nogncheck
  41. #endif
  42. namespace tracing {
  43. namespace {
  44. const char kPerfettoTestDataSourceName[] =
  45. "org.chromium.chrome_integration_unittest";
  46. std::string GetPerfettoProducerName() {
  47. return base::StrCat({mojom::kPerfettoProducerNamePrefix, "123"});
  48. }
  49. std::string RandomASCII(size_t length) {
  50. std::string tmp;
  51. for (size_t i = 0; i < length; ++i) {
  52. tmp += base::RandInt('a', 'z');
  53. }
  54. return tmp;
  55. }
  56. class ClearAndRestoreSystemProducerScope {
  57. public:
  58. ClearAndRestoreSystemProducerScope() {
  59. base::RunLoop setup_loop;
  60. PerfettoTracedProcess::GetTaskRunner()->GetOrCreateTaskRunner()->PostTask(
  61. FROM_HERE, base::BindLambdaForTesting([this, &setup_loop] {
  62. saved_producer_ =
  63. PerfettoTracedProcess::Get()->SetSystemProducerForTesting(
  64. nullptr);
  65. setup_loop.Quit();
  66. }));
  67. setup_loop.Run();
  68. }
  69. ~ClearAndRestoreSystemProducerScope() {
  70. base::RunLoop destroy_loop;
  71. PerfettoTracedProcess::GetTaskRunner()->GetOrCreateTaskRunner()->PostTask(
  72. FROM_HERE, base::BindLambdaForTesting([this, &destroy_loop]() {
  73. PerfettoTracedProcess::Get()
  74. ->SetSystemProducerForTesting(std::move(saved_producer_))
  75. .reset();
  76. destroy_loop.Quit();
  77. }));
  78. destroy_loop.Run();
  79. }
  80. private:
  81. std::unique_ptr<SystemProducer> saved_producer_;
  82. };
  83. class SystemPerfettoTest : public TracingUnitTest {
  84. public:
  85. void SetUp() override {
  86. TracingUnitTest::SetUp();
  87. EXPECT_TRUE(tmp_dir_.CreateUniqueTempDir());
  88. // We need to set TMPDIR environment variable because when a new producer
  89. // connects to the perfetto service it needs to create a memmap'd file for
  90. // the shared memory buffer. Setting TMPDIR allows the service to know
  91. // where this should be.
  92. //
  93. // Finally since environment variables are leaked into other tests if
  94. // multiple tests run we need to restore the value so each test is
  95. // hermetic.
  96. old_tmp_dir_ = getenv("TMPDIR");
  97. setenv("TMPDIR", tmp_dir_.GetPath().value().c_str(), true);
  98. // Set up the system socket locations in a valid tmp directory.
  99. producer_socket_ =
  100. tmp_dir_.GetPath().Append(FILE_PATH_LITERAL("producer")).value();
  101. consumer_socket_ =
  102. tmp_dir_.GetPath().Append(FILE_PATH_LITERAL("consumer")).value();
  103. // Construct three default TestDataSources which write out different amount
  104. // of packets to make it easy to verify which data source has written
  105. // packets.
  106. data_sources_.push_back(TestDataSource::CreateAndRegisterDataSource(
  107. kPerfettoTestDataSourceName, 1));
  108. data_sources_.push_back(TestDataSource::CreateAndRegisterDataSource(
  109. base::StrCat({kPerfettoTestDataSourceName, "1"}), 3));
  110. data_sources_.push_back(TestDataSource::CreateAndRegisterDataSource(
  111. base::StrCat({kPerfettoTestDataSourceName, "2"}), 7));
  112. // Construct the service and wait for it to completely set up.
  113. perfetto_service_ = std::make_unique<PerfettoService>();
  114. RunUntilIdle();
  115. }
  116. void TearDown() override {
  117. data_sources_.clear();
  118. perfetto_service_.reset();
  119. if (old_tmp_dir_) {
  120. // Restore the old value back to its initial value.
  121. setenv("TMPDIR", old_tmp_dir_, true);
  122. } else {
  123. // TMPDIR wasn't set originally so unset it.
  124. unsetenv("TMPDIR");
  125. }
  126. TracingUnitTest::TearDown();
  127. }
  128. std::unique_ptr<MockPosixSystemProducer> CreateMockPosixSystemProducer(
  129. MockSystemService* service,
  130. int num_data_sources_expected = 0,
  131. base::RunLoop* system_data_source_enabled_runloop = nullptr,
  132. base::RunLoop* system_data_source_disabled_runloop = nullptr,
  133. bool check_sdk_level = false,
  134. bool sandbox_forbids_socket_connection = false) {
  135. std::unique_ptr<MockPosixSystemProducer> result;
  136. base::RunLoop loop_finished;
  137. // When we construct a MockPosixSystemProducer it needs to be on the
  138. // correct sequence. Construct it on the task runner and wait on the
  139. // |loop_finished| to ensure it is completely set up.
  140. PerfettoTracedProcess::GetTaskRunner()
  141. ->GetOrCreateTaskRunner()
  142. ->PostTaskAndReply(
  143. FROM_HERE, base::BindLambdaForTesting([&]() {
  144. result = std::make_unique<MockPosixSystemProducer>(
  145. service->producer(), check_sdk_level,
  146. num_data_sources_expected,
  147. system_data_source_enabled_runloop
  148. ? base::BindOnce(
  149. [](base::RunLoop* loop) { loop->Quit(); },
  150. system_data_source_enabled_runloop)
  151. : base::OnceClosure(),
  152. system_data_source_disabled_runloop
  153. ? base::BindOnce(
  154. [](base::RunLoop* loop) { loop->Quit(); },
  155. system_data_source_disabled_runloop)
  156. : base::OnceClosure(),
  157. sandbox_forbids_socket_connection);
  158. }),
  159. loop_finished.QuitClosure());
  160. loop_finished.Run();
  161. DCHECK(result);
  162. return result;
  163. }
  164. std::unique_ptr<MockSystemService> CreateMockSystemService() {
  165. return std::make_unique<MockSystemService>(consumer_socket_,
  166. producer_socket_);
  167. }
  168. PerfettoService* local_service() const { return perfetto_service_.get(); }
  169. // Fork() + executes the perfetto cmdline client with the given args and
  170. // returns true if we exited with a success otherwise |stderr_| is populated
  171. // with the reason for the failure.
  172. bool ExecPerfetto(std::initializer_list<std::string> args,
  173. std::string config) {
  174. stderr_.clear();
  175. base::CommandLine cmd(base::FilePath("/system/bin/perfetto"));
  176. for (auto& arg : args) {
  177. cmd.AppendArg(std::move(arg));
  178. }
  179. std::string config_path =
  180. tmp_dir_.GetPath().Append(FILE_PATH_LITERAL("trace_config")).value();
  181. config_path += RandomASCII(16);
  182. cmd.AppendArgPath(base::FilePath(config_path));
  183. base::File config_file(
  184. base::FilePath(config_path),
  185. base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
  186. if (!config_file.IsValid()) {
  187. stderr_ = "Tried to create ";
  188. stderr_ += config_path;
  189. stderr_ += " but failed with error ";
  190. stderr_ += base::File::ErrorToString(config_file.error_details());
  191. return false;
  192. }
  193. size_t written = config_file.Write(0, config.data(), config.size());
  194. if (written != config.size()) {
  195. stderr_ = base::StrCat({"Expected ", base::NumberToString(config.size()),
  196. " bytes written but actually wrote ",
  197. base::NumberToString(written)});
  198. return false;
  199. }
  200. config_file.Close();
  201. bool succeeded = base::GetAppOutputAndError(cmd, &stderr_);
  202. if (!succeeded) {
  203. stderr_ +=
  204. " !!! end of |stderr_| this was generated by the commandline: ";
  205. stderr_ += cmd.GetCommandLineString();
  206. }
  207. // This just cleans up the config file we generated above.
  208. EXPECT_EQ(0, remove(config_path.c_str()));
  209. return succeeded;
  210. }
  211. protected:
  212. // |tmp_dir_| must be destroyed last. So must be declared first.
  213. base::ScopedTempDir tmp_dir_;
  214. std::string producer_socket_;
  215. std::string consumer_socket_;
  216. std::unique_ptr<PerfettoService> perfetto_service_;
  217. std::vector<std::unique_ptr<TestDataSource>> data_sources_;
  218. std::string stderr_;
  219. const char* old_tmp_dir_ = nullptr;
  220. };
  221. #if BUILDFLAG(IS_ANDROID)
  222. // Flaky on Android: crbug.com/1262132#c17
  223. #define MAYBE_SystemTraceEndToEnd DISABLED_SystemTraceEndToEnd
  224. #else
  225. #define MAYBE_SystemTraceEndToEnd SystemTraceEndToEnd
  226. #endif
  227. TEST_F(SystemPerfettoTest, MAYBE_SystemTraceEndToEnd) {
  228. auto system_service = CreateMockSystemService();
  229. // Set up the producer to talk to the system.
  230. base::RunLoop system_data_source_enabled_runloop;
  231. base::RunLoop system_data_source_disabled_runloop;
  232. auto system_producer = CreateMockPosixSystemProducer(
  233. system_service.get(),
  234. /* num_data_sources_expected = */ 1, &system_data_source_enabled_runloop,
  235. &system_data_source_disabled_runloop);
  236. // Start a system trace, and wait on the Data Source being started.
  237. base::RunLoop system_no_more_packets_runloop;
  238. MockConsumer system_consumer(
  239. {kPerfettoTestDataSourceName}, system_service->GetService(),
  240. [&system_no_more_packets_runloop](bool has_more) {
  241. if (!has_more) {
  242. system_no_more_packets_runloop.Quit();
  243. }
  244. });
  245. system_data_source_enabled_runloop.Run();
  246. system_consumer.WaitForAllDataSourcesStarted();
  247. // Post a task to ensure we stop the trace after the data is written.
  248. base::RunLoop stop_tracing;
  249. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  250. [&system_consumer, &stop_tracing]() {
  251. system_consumer.StopTracing();
  252. stop_tracing.Quit();
  253. });
  254. stop_tracing.Run();
  255. system_data_source_disabled_runloop.Run();
  256. system_no_more_packets_runloop.Run();
  257. system_consumer.WaitForAllDataSourcesStopped();
  258. EXPECT_EQ(1u, system_consumer.received_test_packets());
  259. PerfettoProducer::DeleteSoonForTesting(std::move(system_producer));
  260. }
  261. #if BUILDFLAG(IS_ANDROID)
  262. // Flaky on Android: crbug.com/1262132#c17
  263. #define MAYBE_OneSystemSourceWithMultipleLocalSources \
  264. DISABLED_OneSystemSourceWithMultipleLocalSources
  265. #else
  266. #define MAYBE_OneSystemSourceWithMultipleLocalSources \
  267. OneSystemSourceWithMultipleLocalSources
  268. #endif
  269. TEST_F(SystemPerfettoTest, MAYBE_OneSystemSourceWithMultipleLocalSources) {
  270. auto system_service = CreateMockSystemService();
  271. // Start a trace using the system Perfetto service.
  272. base::RunLoop system_no_more_packets_runloop;
  273. MockConsumer system_consumer(
  274. {kPerfettoTestDataSourceName}, system_service->GetService(),
  275. [&system_no_more_packets_runloop](bool has_more) {
  276. if (!has_more) {
  277. system_no_more_packets_runloop.Quit();
  278. }
  279. });
  280. base::RunLoop system_data_source_enabled_runloop;
  281. base::RunLoop system_data_source_disabled_runloop;
  282. auto system_producer = CreateMockPosixSystemProducer(
  283. system_service.get(),
  284. /* num_data_sources_expected = */ 1, &system_data_source_enabled_runloop,
  285. &system_data_source_disabled_runloop);
  286. system_data_source_enabled_runloop.Run();
  287. system_consumer.WaitForAllDataSourcesStarted();
  288. // Now start the local trace and wait for the system trace to stop first.
  289. base::RunLoop local_data_source_enabled_runloop;
  290. base::RunLoop local_data_source_disabled_runloop;
  291. base::RunLoop local_no_more_packets_runloop;
  292. std::unique_ptr<MockProducerClient::Handle> local_producer_client =
  293. MockProducerClient::Create(
  294. /* num_data_sources = */ 3,
  295. local_data_source_enabled_runloop.QuitClosure(),
  296. local_data_source_disabled_runloop.QuitClosure());
  297. MockConsumer local_consumer(
  298. {kPerfettoTestDataSourceName,
  299. base::StrCat({kPerfettoTestDataSourceName, "1"}),
  300. base::StrCat({kPerfettoTestDataSourceName, "2"})},
  301. local_service()->GetService(),
  302. [&local_no_more_packets_runloop](bool has_more) {
  303. if (!has_more) {
  304. local_no_more_packets_runloop.Quit();
  305. }
  306. });
  307. auto local_producer_host = std::make_unique<MockProducerHost>(
  308. GetPerfettoProducerName(), kPerfettoTestDataSourceName, local_service(),
  309. **local_producer_client);
  310. system_consumer.WaitForAllDataSourcesStopped();
  311. system_data_source_disabled_runloop.Run();
  312. local_consumer.WaitForAllDataSourcesStarted();
  313. local_data_source_enabled_runloop.Run();
  314. // Ensures that the Trace data gets written and committed.
  315. RunUntilIdle();
  316. // Once we StopTracing() on the local trace the system tracing system will
  317. // come back. So set new enabled and disabled RunLoops for the system
  318. // producer.
  319. base::RunLoop system_data_source_reenabled_runloop;
  320. base::RunLoop system_data_source_redisabled_runloop;
  321. system_producer->SetDataSourceEnabledCallback(
  322. system_data_source_reenabled_runloop.QuitClosure());
  323. system_producer->SetDataSourceDisabledCallback(
  324. system_data_source_redisabled_runloop.QuitClosure());
  325. base::RunLoop system_data_source_wrote_data_runloop;
  326. data_sources_[0]->set_start_tracing_callback(
  327. system_data_source_wrote_data_runloop.QuitClosure());
  328. local_consumer.StopTracing();
  329. local_data_source_disabled_runloop.Run();
  330. local_consumer.WaitForAllDataSourcesStopped();
  331. local_no_more_packets_runloop.Run();
  332. // Wait for system tracing to return before stopping the trace on the correct
  333. // sequence to ensure everything is committed.
  334. system_data_source_reenabled_runloop.Run();
  335. system_consumer.WaitForAllDataSourcesStarted();
  336. base::RunLoop stop_tracing;
  337. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  338. [&system_consumer, &stop_tracing]() {
  339. system_consumer.StopTracing();
  340. stop_tracing.Quit();
  341. });
  342. stop_tracing.Run();
  343. system_data_source_redisabled_runloop.Run();
  344. system_consumer.WaitForAllDataSourcesStopped();
  345. system_no_more_packets_runloop.Run();
  346. // |local_consumer| should have seen one |send_packet_count_| from each data
  347. // source, whereas |system_consumer| should see 2 packets from the first data
  348. // source having been started twice.
  349. EXPECT_EQ(1u + 3u + 7u, local_consumer.received_test_packets());
  350. EXPECT_EQ(2u, system_consumer.received_test_packets());
  351. PerfettoProducer::DeleteSoonForTesting(std::move(system_producer));
  352. }
  353. #if BUILDFLAG(IS_ANDROID)
  354. // Flaky on Android: crbug.com/1262132#c17
  355. #define MAYBE_MultipleSystemSourceWithOneLocalSourcesLocalFirst \
  356. DISABLED_MultipleSystemSourceWithOneLocalSourcesLocalFirst
  357. #else
  358. #define MAYBE_MultipleSystemSourceWithOneLocalSourcesLocalFirst \
  359. MultipleSystemSourceWithOneLocalSourcesLocalFirst
  360. #endif
  361. TEST_F(SystemPerfettoTest,
  362. MAYBE_MultipleSystemSourceWithOneLocalSourcesLocalFirst) {
  363. auto system_service = CreateMockSystemService();
  364. base::RunLoop local_no_more_packets_runloop;
  365. std::unique_ptr<MockConsumer> local_consumer(
  366. new MockConsumer({base::StrCat({kPerfettoTestDataSourceName, "2"})},
  367. local_service()->GetService(),
  368. [&local_no_more_packets_runloop](bool has_more) {
  369. if (!has_more) {
  370. local_no_more_packets_runloop.Quit();
  371. }
  372. }));
  373. // Now start the local trace and wait for the system trace to stop first.
  374. base::RunLoop local_data_source_enabled_runloop;
  375. base::RunLoop local_data_source_disabled_runloop;
  376. std::unique_ptr<MockProducerClient::Handle> local_producer_client =
  377. MockProducerClient::Create(
  378. /* num_data_sources = */ 1,
  379. local_data_source_enabled_runloop.QuitClosure(),
  380. local_data_source_disabled_runloop.QuitClosure());
  381. auto local_producer_host = std::make_unique<MockProducerHost>(
  382. GetPerfettoProducerName(), kPerfettoTestDataSourceName, local_service(),
  383. **local_producer_client);
  384. local_data_source_enabled_runloop.Run();
  385. local_consumer->WaitForAllDataSourcesStarted();
  386. // Ensures that the Trace data gets written and committed.
  387. RunUntilIdle();
  388. local_consumer->StopTracing();
  389. local_data_source_disabled_runloop.Run();
  390. local_consumer->WaitForAllDataSourcesStopped();
  391. local_no_more_packets_runloop.Run();
  392. EXPECT_EQ(7u, local_consumer->received_test_packets());
  393. // Because we can't just use |system_data_source_enabled| because they might
  394. // attempt to enable but be queued until the local trace has fully finished.
  395. // We therefore need to set callbacks explicitly after the data has been
  396. // written.
  397. std::vector<base::RunLoop> data_sources_wrote_data{data_sources_.size()};
  398. for (size_t i = 0; i < data_sources_.size(); ++i) {
  399. data_sources_[i]->set_start_tracing_callback(
  400. data_sources_wrote_data[i].QuitClosure());
  401. }
  402. // Start a trace using the system Perfetto service.
  403. base::RunLoop system_no_more_packets_runloop;
  404. MockConsumer system_consumer(
  405. {kPerfettoTestDataSourceName,
  406. base::StrCat({kPerfettoTestDataSourceName, "1"}),
  407. base::StrCat({kPerfettoTestDataSourceName, "2"})},
  408. system_service->GetService(),
  409. [&system_no_more_packets_runloop](bool has_more) {
  410. if (!has_more) {
  411. system_no_more_packets_runloop.Quit();
  412. }
  413. });
  414. base::RunLoop system_data_source_enabled_runloop;
  415. base::RunLoop system_data_source_disabled_runloop;
  416. auto system_producer = CreateMockPosixSystemProducer(
  417. system_service.get(),
  418. /* num_data_sources_expected = */ 3, &system_data_source_enabled_runloop,
  419. &system_data_source_disabled_runloop);
  420. system_data_source_enabled_runloop.Run();
  421. for (auto& loop : data_sources_wrote_data) {
  422. loop.Run();
  423. }
  424. system_consumer.WaitForAllDataSourcesStarted();
  425. // Wait for system tracing to return before stopping the trace on the correct
  426. // sequence to ensure everything is committed.
  427. base::RunLoop stop_tracing;
  428. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  429. [&system_consumer, &stop_tracing]() {
  430. system_consumer.StopTracing();
  431. stop_tracing.Quit();
  432. });
  433. stop_tracing.Run();
  434. system_data_source_disabled_runloop.Run();
  435. system_consumer.WaitForAllDataSourcesStopped();
  436. system_no_more_packets_runloop.Run();
  437. // Once we StopTracing() on the system trace the we want to make sure a new
  438. // local trace can start smoothly. So set new enabled and disabled RunLoops
  439. // for the system producer.
  440. base::RunLoop local_data_source_reenabled_runloop;
  441. base::RunLoop local_data_source_redisabled_runloop;
  442. (*local_producer_client)
  443. ->SetAgentEnabledCallback(
  444. local_data_source_reenabled_runloop.QuitClosure());
  445. (*local_producer_client)
  446. ->SetAgentDisabledCallback(
  447. local_data_source_redisabled_runloop.QuitClosure());
  448. local_consumer->FreeBuffers();
  449. local_consumer->StartTracing();
  450. local_data_source_reenabled_runloop.Run();
  451. local_consumer->WaitForAllDataSourcesStarted();
  452. local_consumer->StopTracing();
  453. local_consumer->WaitForAllDataSourcesStopped();
  454. local_data_source_redisabled_runloop.Run();
  455. // |local_consumer| should have seen one |send_packet_count_| from each data
  456. // source, whereas |system_consumer| should see 2 packets from the first data
  457. // source having been started twice.
  458. EXPECT_EQ(14u, local_consumer->received_test_packets());
  459. EXPECT_EQ(1u + 3u + 7u, system_consumer.received_test_packets());
  460. PerfettoProducer::DeleteSoonForTesting(std::move(system_producer));
  461. }
  462. #if BUILDFLAG(IS_ANDROID)
  463. // Flaky on Android: crbug.com/1262132#c17
  464. #define MAYBE_MultipleSystemAndLocalSources \
  465. DISABLED_MultipleSystemAndLocalSources
  466. #else
  467. #define MAYBE_MultipleSystemAndLocalSources MultipleSystemAndLocalSources
  468. #endif
  469. TEST_F(SystemPerfettoTest, MAYBE_MultipleSystemAndLocalSources) {
  470. auto system_service = CreateMockSystemService();
  471. // Start a trace using the system Perfetto service.
  472. base::RunLoop system_no_more_packets_runloop;
  473. MockConsumer system_consumer(
  474. {kPerfettoTestDataSourceName,
  475. base::StrCat({kPerfettoTestDataSourceName, "1"}),
  476. base::StrCat({kPerfettoTestDataSourceName, "2"})},
  477. system_service->GetService(),
  478. [&system_no_more_packets_runloop](bool has_more) {
  479. if (!has_more) {
  480. system_no_more_packets_runloop.Quit();
  481. }
  482. });
  483. base::RunLoop system_data_source_enabled_runloop;
  484. base::RunLoop system_data_source_disabled_runloop;
  485. auto system_producer = CreateMockPosixSystemProducer(
  486. system_service.get(),
  487. /* num_data_sources_expected = */ 3, &system_data_source_enabled_runloop,
  488. &system_data_source_disabled_runloop);
  489. system_data_source_enabled_runloop.Run();
  490. system_consumer.WaitForAllDataSourcesStarted();
  491. // Now start the local trace and wait for the system trace to stop first.
  492. base::RunLoop local_data_source_enabled_runloop;
  493. base::RunLoop local_data_source_disabled_runloop;
  494. base::RunLoop local_no_more_packets_runloop;
  495. std::unique_ptr<MockProducerClient::Handle> local_producer_client =
  496. MockProducerClient::Create(
  497. /* num_data_sources = */ 3,
  498. local_data_source_enabled_runloop.QuitClosure(),
  499. local_data_source_disabled_runloop.QuitClosure());
  500. auto local_producer_host = std::make_unique<MockProducerHost>(
  501. GetPerfettoProducerName(), kPerfettoTestDataSourceName, local_service(),
  502. **local_producer_client);
  503. MockConsumer local_consumer(
  504. {kPerfettoTestDataSourceName,
  505. base::StrCat({kPerfettoTestDataSourceName, "1"}),
  506. base::StrCat({kPerfettoTestDataSourceName, "2"})},
  507. local_service()->GetService(),
  508. [&local_no_more_packets_runloop](bool has_more) {
  509. if (!has_more) {
  510. local_no_more_packets_runloop.Quit();
  511. }
  512. });
  513. system_data_source_disabled_runloop.Run();
  514. system_consumer.WaitForAllDataSourcesStopped();
  515. local_data_source_enabled_runloop.Run();
  516. local_consumer.WaitForAllDataSourcesStarted();
  517. // Ensures that the Trace data gets written and committed.
  518. RunUntilIdle();
  519. // Once we StopTracing() on the local trace the system tracing system will
  520. // come back. So set new enabled and disabled RunLoops for the system
  521. // producer.
  522. base::RunLoop system_data_source_reenabled_runloop;
  523. base::RunLoop system_data_source_redisabled_runloop;
  524. system_producer->SetDataSourceEnabledCallback(
  525. system_data_source_reenabled_runloop.QuitClosure());
  526. system_producer->SetDataSourceDisabledCallback(
  527. system_data_source_redisabled_runloop.QuitClosure());
  528. // |system_data_source_enabled| is called by the MockPosixSystemProducer after
  529. // calling PosixSystemProducer::StartDataSource, BUT
  530. // PosixSystemProducer::StartDataSource could not actual start the DataSource
  531. // if local tracing hasn't yet finished. So waiting for data to be written
  532. // (and thus implying the data source has started) is a better option.
  533. std::vector<base::RunLoop> data_sources_wrote_data{data_sources_.size()};
  534. for (size_t i = 0; i < data_sources_.size(); ++i) {
  535. data_sources_[i]->set_start_tracing_callback(
  536. data_sources_wrote_data[i].QuitClosure());
  537. }
  538. local_consumer.StopTracing();
  539. local_data_source_disabled_runloop.Run();
  540. local_consumer.WaitForAllDataSourcesStopped();
  541. local_no_more_packets_runloop.Run();
  542. // Wait for system tracing to return before stopping.
  543. system_data_source_reenabled_runloop.Run();
  544. for (auto& loop : data_sources_wrote_data) {
  545. loop.Run();
  546. }
  547. system_consumer.WaitForAllDataSourcesStarted();
  548. base::RunLoop stop_tracing;
  549. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  550. [&system_consumer, &stop_tracing]() {
  551. system_consumer.StopTracing();
  552. stop_tracing.Quit();
  553. });
  554. stop_tracing.Run();
  555. system_data_source_redisabled_runloop.Run();
  556. system_no_more_packets_runloop.Run();
  557. // |local_consumer| should have seen one |send_packet_count_| from each data
  558. // source, whereas |system_consumer| should see 2 packets from each since it
  559. // got started twice.
  560. EXPECT_EQ(1u + 3u + 7u, local_consumer.received_test_packets());
  561. EXPECT_EQ((1u + 3u + 7u) * 2, system_consumer.received_test_packets());
  562. PerfettoProducer::DeleteSoonForTesting(std::move(system_producer));
  563. }
  564. #if BUILDFLAG(IS_ANDROID)
  565. // Flaky on Android: crbug.com/1262132#c17
  566. #define MAYBE_MultipleSystemAndLocalSourcesLocalFirst \
  567. DISABLED_MultipleSystemAndLocalSourcesLocalFirst
  568. #else
  569. #define MAYBE_MultipleSystemAndLocalSourcesLocalFirst \
  570. MultipleSystemAndLocalSourcesLocalFirst
  571. #endif
  572. TEST_F(SystemPerfettoTest, MAYBE_MultipleSystemAndLocalSourcesLocalFirst) {
  573. auto system_service = CreateMockSystemService();
  574. // We construct it up front so it connects to the service before the local
  575. // trace starts.
  576. base::RunLoop system_data_source_enabled_runloop;
  577. base::RunLoop system_data_source_disabled_runloop;
  578. auto system_producer = CreateMockPosixSystemProducer(
  579. system_service.get(),
  580. /* num_data_sources_expected = */ 3, &system_data_source_enabled_runloop,
  581. &system_data_source_disabled_runloop);
  582. // Now start the local trace and wait for the system trace to stop first.
  583. base::RunLoop local_data_source_enabled_runloop;
  584. base::RunLoop local_data_source_disabled_runloop;
  585. base::RunLoop local_no_more_packets_runloop;
  586. std::unique_ptr<MockProducerClient::Handle> local_producer_client =
  587. MockProducerClient::Create(
  588. /* num_data_sources = */ 3,
  589. local_data_source_enabled_runloop.QuitClosure(),
  590. local_data_source_disabled_runloop.QuitClosure());
  591. auto local_producer_host = std::make_unique<MockProducerHost>(
  592. GetPerfettoProducerName(), kPerfettoTestDataSourceName, local_service(),
  593. **local_producer_client);
  594. MockConsumer local_consumer(
  595. {kPerfettoTestDataSourceName,
  596. base::StrCat({kPerfettoTestDataSourceName, "1"}),
  597. base::StrCat({kPerfettoTestDataSourceName, "2"})},
  598. local_service()->GetService(),
  599. [&local_no_more_packets_runloop](bool has_more) {
  600. if (!has_more) {
  601. local_no_more_packets_runloop.Quit();
  602. }
  603. });
  604. local_data_source_enabled_runloop.Run();
  605. local_consumer.WaitForAllDataSourcesStarted();
  606. // Ensures that the Trace data gets written and committed.
  607. RunUntilIdle();
  608. // Because we can't just use |system_data_source_enabled| because they might
  609. // attempt to enable but be queued until the local trace has fully finished.
  610. // We therefore need to set callbacks explicitly after the data has been
  611. // written.
  612. std::vector<base::RunLoop> data_sources_wrote_data{data_sources_.size()};
  613. for (size_t i = 0; i < data_sources_.size(); ++i) {
  614. data_sources_[i]->set_start_tracing_callback(
  615. data_sources_wrote_data[i].QuitClosure());
  616. }
  617. // Start a trace using the system Perfetto service.
  618. base::RunLoop system_no_more_packets_runloop;
  619. MockConsumer system_consumer(
  620. {kPerfettoTestDataSourceName,
  621. base::StrCat({kPerfettoTestDataSourceName, "1"}),
  622. base::StrCat({kPerfettoTestDataSourceName, "2"})},
  623. system_service->GetService(),
  624. [&system_no_more_packets_runloop](bool has_more) {
  625. if (!has_more) {
  626. system_no_more_packets_runloop.Quit();
  627. }
  628. });
  629. // Post a task to ensure all the connection logic has been run.
  630. base::RunLoop local_stop_tracing;
  631. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  632. [&local_consumer, &local_stop_tracing]() {
  633. local_consumer.StopTracing();
  634. local_stop_tracing.Quit();
  635. });
  636. local_stop_tracing.Run();
  637. local_data_source_disabled_runloop.Run();
  638. local_consumer.WaitForAllDataSourcesStopped();
  639. local_no_more_packets_runloop.Run();
  640. // Now the system trace will start.
  641. system_data_source_enabled_runloop.Run();
  642. for (auto& loop : data_sources_wrote_data) {
  643. loop.Run();
  644. }
  645. system_consumer.WaitForAllDataSourcesStarted();
  646. // Wait for system tracing to return before stopping.
  647. base::RunLoop system_stop_tracing;
  648. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  649. [&system_consumer, &system_stop_tracing]() {
  650. system_consumer.StopTracing();
  651. system_stop_tracing.Quit();
  652. });
  653. system_stop_tracing.Run();
  654. system_data_source_disabled_runloop.Run();
  655. system_consumer.WaitForAllDataSourcesStopped();
  656. system_no_more_packets_runloop.Run();
  657. // |local_consumer| & |system_consumer| should have seen one
  658. // |send_packet_count_| from each data source.
  659. EXPECT_EQ(1u + 3u + 7u, local_consumer.received_test_packets());
  660. EXPECT_EQ(1u + 3u + 7u, system_consumer.received_test_packets());
  661. PerfettoProducer::DeleteSoonForTesting(std::move(system_producer));
  662. }
  663. #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  664. // Flaky on all CrOS platforms: crbug.com/1262132#c18
  665. // Flaky on Android: crbug.com/1262132
  666. #define MAYBE_SystemTraceWhileLocalStartupTracing \
  667. DISABLED_SystemTraceWhileLocalStartupTracing
  668. #else
  669. #define MAYBE_SystemTraceWhileLocalStartupTracing \
  670. SystemTraceWhileLocalStartupTracing
  671. #endif
  672. // Attempts to start a system trace while a local startup trace is active. The
  673. // system trace should only be started after the local trace is completed.
  674. TEST_F(SystemPerfettoTest, MAYBE_SystemTraceWhileLocalStartupTracing) {
  675. // We're using mojom::kTraceEventDataSourceName for the local producer to
  676. // emulate starting the real TraceEventDataSource which owns startup tracing.
  677. auto mock_trace_event_ds = TestDataSource::CreateAndRegisterDataSource(
  678. mojom::kTraceEventDataSourceName, 2);
  679. // Wait for data source to register.
  680. RunUntilIdle();
  681. auto system_service = CreateMockSystemService();
  682. // Create local producer.
  683. base::RunLoop local_data_source_enabled_runloop;
  684. base::RunLoop local_data_source_disabled_runloop;
  685. auto local_producer = MockProducerClient::Create(
  686. /* num_data_sources = */ 1,
  687. local_data_source_enabled_runloop.QuitClosure(),
  688. local_data_source_disabled_runloop.QuitClosure());
  689. // Setup startup tracing for local producer.
  690. CHECK((*local_producer)
  691. ->SetupStartupTracing(base::trace_event::TraceConfig(),
  692. /*privacy_filtering_enabled=*/false));
  693. // Attempt to start a system tracing session. Because startup tracing is
  694. // already active, the system producer shouldn't activate yet.
  695. base::RunLoop system_no_more_packets_runloop;
  696. MockConsumer system_consumer(
  697. {kPerfettoTestDataSourceName}, system_service->GetService(),
  698. [&system_no_more_packets_runloop](bool has_more) {
  699. if (!has_more) {
  700. system_no_more_packets_runloop.Quit();
  701. }
  702. });
  703. base::RunLoop system_data_source_enabled_runloop;
  704. base::RunLoop system_data_source_disabled_runloop;
  705. auto system_producer = CreateMockPosixSystemProducer(
  706. system_service.get(),
  707. /* num_data_sources_expected = */ 1, &system_data_source_enabled_runloop,
  708. &system_data_source_disabled_runloop);
  709. RunUntilIdle();
  710. // Now connect the local ProducerHost & consumer, taking over startup tracing.
  711. base::RunLoop local_no_more_packets_runloop;
  712. std::unique_ptr<MockConsumer> local_consumer(new MockConsumer(
  713. {mojom::kTraceEventDataSourceName}, local_service()->GetService(),
  714. [&local_no_more_packets_runloop](bool has_more) {
  715. if (!has_more) {
  716. local_no_more_packets_runloop.Quit();
  717. }
  718. }));
  719. auto local_producer_host = std::make_unique<MockProducerHost>(
  720. GetPerfettoProducerName(), mojom::kTraceEventDataSourceName,
  721. local_service(), **local_producer);
  722. local_data_source_enabled_runloop.Run();
  723. local_consumer->WaitForAllDataSourcesStarted();
  724. // Ensures that the Trace data gets written and committed.
  725. RunUntilIdle();
  726. // Stop local session. This should reconnect the system producer & start the
  727. // system session.
  728. local_consumer->StopTracing();
  729. local_data_source_disabled_runloop.Run();
  730. local_consumer->WaitForAllDataSourcesStopped();
  731. local_no_more_packets_runloop.Run();
  732. // Local consumer should have received 2 packets from |mock_trace_event_ds|.
  733. EXPECT_EQ(2u, local_consumer->received_test_packets());
  734. // Wait for system producer to get enabled. Wait have to wait for the
  735. // individual data source to write data, because it might be queued until the
  736. // local trace has fully finished.
  737. base::RunLoop system_data_source_wrote_data_runloop;
  738. data_sources_[0]->set_start_tracing_callback(
  739. system_data_source_wrote_data_runloop.QuitClosure());
  740. system_data_source_enabled_runloop.Run();
  741. system_data_source_wrote_data_runloop.Run();
  742. system_consumer.WaitForAllDataSourcesStarted();
  743. // Stop the trace on the correct sequence to ensure everything is committed.
  744. base::RunLoop stop_tracing;
  745. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  746. [&system_consumer, &stop_tracing]() {
  747. system_consumer.StopTracing();
  748. stop_tracing.Quit();
  749. });
  750. stop_tracing.Run();
  751. system_data_source_disabled_runloop.Run();
  752. system_consumer.WaitForAllDataSourcesStopped();
  753. system_no_more_packets_runloop.Run();
  754. // Local consumer should have received 1 packet from the |data_sources_[0]|.
  755. EXPECT_EQ(1u, system_consumer.received_test_packets());
  756. PerfettoProducer::DeleteSoonForTesting(std::move(system_producer));
  757. }
  758. #if BUILDFLAG(IS_ANDROID)
  759. // Failing on android-pie-arm64-dbg, see crbug.com/1262132.
  760. TEST_F(SystemPerfettoTest, DISABLED_SystemToLowAPILevel) {
  761. if (base::android::BuildInfo::GetInstance()->sdk_int() >=
  762. base::android::SDK_VERSION_P) {
  763. LOG(INFO) << "Skipping SystemToLowAPILevel test, this phone supports the "
  764. << "P SDK (or above).";
  765. // This test will do exactly the same thing on versions beyond P so just
  766. // exit. Once we are no longer testing on O and below we can remove this
  767. // test.
  768. return;
  769. }
  770. auto run_test = [this](bool check_sdk_level) {
  771. PerfettoTracedProcess::Get()->ClearDataSourcesForTesting();
  772. std::string data_source_name = "temp_name";
  773. data_source_name += check_sdk_level ? "true" : "false";
  774. base::RunLoop data_source_started_runloop;
  775. std::unique_ptr<TestDataSource> data_source =
  776. TestDataSource::CreateAndRegisterDataSource(data_source_name, 1);
  777. data_source->set_start_tracing_callback(
  778. data_source_started_runloop.QuitClosure());
  779. auto system_service = CreateMockSystemService();
  780. base::RunLoop system_no_more_packets_runloop;
  781. MockConsumer system_consumer(
  782. {data_source_name}, system_service->GetService(),
  783. [&system_no_more_packets_runloop](bool has_more) {
  784. if (!has_more) {
  785. system_no_more_packets_runloop.Quit();
  786. }
  787. });
  788. base::RunLoop system_data_source_enabled_runloop;
  789. base::RunLoop system_data_source_disabled_runloop;
  790. auto system_producer = CreateMockPosixSystemProducer(
  791. system_service.get(),
  792. /* num_data_sources_expected = */ 1,
  793. &system_data_source_enabled_runloop,
  794. &system_data_source_disabled_runloop, check_sdk_level);
  795. if (!check_sdk_level) {
  796. system_data_source_enabled_runloop.Run();
  797. data_source_started_runloop.Run();
  798. system_consumer.WaitForAllDataSourcesStarted();
  799. }
  800. // Post the task to ensure that the data will have been written and
  801. // committed if any tracing is being done.
  802. base::RunLoop stop_tracing;
  803. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  804. [&system_consumer, &stop_tracing]() {
  805. system_consumer.StopTracing();
  806. stop_tracing.Quit();
  807. });
  808. stop_tracing.Run();
  809. if (!check_sdk_level) {
  810. system_data_source_disabled_runloop.Run();
  811. system_consumer.WaitForAllDataSourcesStopped();
  812. }
  813. system_no_more_packets_runloop.Run();
  814. PerfettoProducer::DeleteSoonForTesting(std::move(system_producer));
  815. return system_consumer.received_test_packets();
  816. };
  817. // If |check_sdk_level| == true, the |system_producer| will not even attempt
  818. // to connect to the |system_service| and therefore we should see no packets.
  819. EXPECT_EQ(1u, run_test(/* check_sdk_level = */ false));
  820. EXPECT_EQ(0u, run_test(/* check_sdk_level = */ true));
  821. }
  822. // Flaky on Android: crbug.com/1262132#c17
  823. TEST_F(SystemPerfettoTest, DISABLED_EnabledOnDebugBuilds) {
  824. base::test::ScopedFeatureList feature_list;
  825. feature_list.InitAndDisableFeature(features::kEnablePerfettoSystemTracing);
  826. if (base::android::BuildInfo::GetInstance()->is_debug_android()) {
  827. EXPECT_TRUE(ShouldSetupSystemTracing());
  828. } else {
  829. EXPECT_FALSE(ShouldSetupSystemTracing());
  830. }
  831. }
  832. #endif // BUILDFLAG(IS_ANDROID)
  833. #if BUILDFLAG(IS_ANDROID)
  834. // Flaky on Android: crbug.com/1262132#c17
  835. #define MAYBE_RespectsFeatureList DISABLED_RespectsFeatureList
  836. #else
  837. #define MAYBE_RespectsFeatureList RespectsFeatureList
  838. #endif
  839. TEST_F(SystemPerfettoTest, MAYBE_RespectsFeatureList) {
  840. #if BUILDFLAG(IS_ANDROID)
  841. if (base::android::BuildInfo::GetInstance()->is_debug_android()) {
  842. // The feature list is ignored on debug android builds so we should have a
  843. // real system producer so just bail out of this test.
  844. EXPECT_TRUE(ShouldSetupSystemTracing());
  845. return;
  846. }
  847. #endif // BUILDFLAG(IS_ANDROID)
  848. {
  849. base::test::ScopedFeatureList feature_list;
  850. feature_list.InitAndEnableFeature(features::kEnablePerfettoSystemTracing);
  851. EXPECT_TRUE(ShouldSetupSystemTracing());
  852. }
  853. {
  854. base::test::ScopedFeatureList feature_list;
  855. feature_list.InitAndDisableFeature(features::kEnablePerfettoSystemTracing);
  856. EXPECT_FALSE(ShouldSetupSystemTracing());
  857. }
  858. }
  859. #if BUILDFLAG(IS_ANDROID)
  860. // Flaky on Android: crbug.com/1262132#c17
  861. TEST_F(SystemPerfettoTest, DISABLED_RespectsFeaturePreAndroidPie) {
  862. if (base::android::BuildInfo::GetInstance()->sdk_int() >=
  863. base::android::SDK_VERSION_P) {
  864. return;
  865. }
  866. auto run_test = [this](bool enable_feature) {
  867. PerfettoTracedProcess::Get()->ClearDataSourcesForTesting();
  868. base::test::ScopedFeatureList feature_list;
  869. if (enable_feature) {
  870. feature_list.InitAndEnableFeature(features::kEnablePerfettoSystemTracing);
  871. } else {
  872. feature_list.InitAndDisableFeature(
  873. features::kEnablePerfettoSystemTracing);
  874. }
  875. std::string data_source_name = "temp_name";
  876. base::RunLoop data_source_started_runloop;
  877. std::unique_ptr<TestDataSource> data_source =
  878. TestDataSource::CreateAndRegisterDataSource(data_source_name, 1);
  879. data_source->set_start_tracing_callback(
  880. data_source_started_runloop.QuitClosure());
  881. auto system_service = CreateMockSystemService();
  882. base::RunLoop system_no_more_packets_runloop;
  883. MockConsumer system_consumer(
  884. {data_source_name}, system_service->GetService(),
  885. [&system_no_more_packets_runloop](bool has_more) {
  886. if (!has_more) {
  887. system_no_more_packets_runloop.Quit();
  888. }
  889. });
  890. base::RunLoop system_data_source_enabled_runloop;
  891. base::RunLoop system_data_source_disabled_runloop;
  892. auto system_producer = CreateMockPosixSystemProducer(
  893. system_service.get(),
  894. /* num_data_sources_expected = */ 1,
  895. &system_data_source_enabled_runloop,
  896. &system_data_source_disabled_runloop, /* check_sdk_level = */ true);
  897. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  898. [&system_producer]() { system_producer->ConnectToSystemService(); });
  899. if (enable_feature) {
  900. system_data_source_enabled_runloop.Run();
  901. data_source_started_runloop.Run();
  902. system_consumer.WaitForAllDataSourcesStarted();
  903. }
  904. // Post the task to ensure that the data will have been written and
  905. // committed if any tracing is being done.
  906. base::RunLoop stop_tracing;
  907. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  908. [&system_consumer, &stop_tracing]() {
  909. system_consumer.StopTracing();
  910. stop_tracing.Quit();
  911. });
  912. stop_tracing.Run();
  913. if (enable_feature) {
  914. system_data_source_disabled_runloop.Run();
  915. system_consumer.WaitForAllDataSourcesStopped();
  916. }
  917. system_no_more_packets_runloop.Run();
  918. PerfettoProducer::DeleteSoonForTesting(std::move(system_producer));
  919. return system_consumer.received_test_packets();
  920. };
  921. EXPECT_EQ(0u, run_test(/* enable_feature = */ false));
  922. EXPECT_EQ(1u, run_test(/* enable_feature = */ true));
  923. }
  924. #endif // BUILDFLAG(IS_ANDROID)
  925. TEST_F(SystemPerfettoTest, DISABLED_EnablePerfettoSystemTracingDefaultState) {
  926. #if BUILDFLAG(IS_CHROMEOS)
  927. EXPECT_EQ(features::kEnablePerfettoSystemTracing.default_state,
  928. base::FEATURE_ENABLED_BY_DEFAULT);
  929. #else
  930. EXPECT_EQ(features::kEnablePerfettoSystemTracing.default_state,
  931. base::FEATURE_DISABLED_BY_DEFAULT);
  932. #endif
  933. }
  934. #if defined(ANDROID)
  935. // Flaky on Android: crbug.com/1262132#c17
  936. #define MAYBE_SetupSystemTracing DISABLED_SetupSystemTracing
  937. #else
  938. #define MAYBE_SetupSystemTracing SetupSystemTracing
  939. #endif
  940. TEST_F(SystemPerfettoTest, MAYBE_SetupSystemTracing) {
  941. ClearAndRestoreSystemProducerScope saved_system_producer;
  942. EXPECT_FALSE(PerfettoTracedProcess::Get()->system_producer());
  943. PerfettoTracedProcess::Get()->SetupSystemTracing();
  944. EXPECT_TRUE(PerfettoTracedProcess::Get()->system_producer());
  945. #if BUILDFLAG(IS_POSIX)
  946. EXPECT_FALSE(PerfettoTracedProcess::Get()
  947. ->system_producer()
  948. ->IsDummySystemProducerForTesting());
  949. #else // BUILDFLAG(IS_POSIX)
  950. EXPECT_TRUE(PerfettoTracedProcess::Get()
  951. ->system_producer()
  952. ->IsDummySystemProducerForTesting());
  953. #endif // BUILDFLAG(IS_POSIX)
  954. }
  955. #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
  956. TEST_F(SystemPerfettoTest, SandboxedOpenProducerSocket) {
  957. const char* kProducerSockEnvName = "PERFETTO_PRODUCER_SOCK_NAME";
  958. auto system_service = CreateMockSystemService();
  959. // Create the Mojo receiver.
  960. auto sts = std::make_unique<SystemTracingService>();
  961. // Override default socket name to make |sts| connect the |system_service|
  962. // correctly.
  963. const char* saved_producer_sock_name = getenv(kProducerSockEnvName);
  964. ASSERT_EQ(
  965. 0, setenv(kProducerSockEnvName, system_service->producer().c_str(), 1));
  966. // Bind the remote and receiver.
  967. PerfettoTracedProcess::GetTaskRunner()->PostTask([&sts]() {
  968. auto remote = sts->BindAndPassPendingRemote();
  969. TracedProcessImpl::GetInstance()->EnableSystemTracingService(
  970. std::move(remote));
  971. });
  972. // Set up the producer to talk to the system.
  973. base::RunLoop system_data_source_enabled_runloop;
  974. base::RunLoop system_data_source_disabled_runloop;
  975. // Create a MockPosixSystemProducer that doesn't make direct socket connection
  976. // but through Mojo.
  977. auto system_producer = CreateMockPosixSystemProducer(
  978. system_service.get(),
  979. /* num_data_sources_expected = */ 1, &system_data_source_enabled_runloop,
  980. &system_data_source_disabled_runloop, false,
  981. /* sandbox_forbids_socket_connection= */ true);
  982. // Start a system trace, and wait on the Data Source being started.
  983. base::RunLoop system_no_more_packets_runloop;
  984. MockConsumer system_consumer(
  985. {kPerfettoTestDataSourceName}, system_service->GetService(),
  986. [&system_no_more_packets_runloop](bool has_more) {
  987. if (!has_more) {
  988. system_no_more_packets_runloop.Quit();
  989. }
  990. });
  991. system_data_source_enabled_runloop.Run();
  992. system_consumer.WaitForAllDataSourcesStarted();
  993. // Post a task to ensure we stop the trace after the data is written.
  994. base::RunLoop stop_tracing;
  995. PerfettoTracedProcess::GetTaskRunner()->PostTask(
  996. [&system_consumer, &stop_tracing, &sts]() {
  997. system_consumer.StopTracing();
  998. // Mojo receiver is bound on the Perfetto task runner.
  999. sts.reset();
  1000. stop_tracing.Quit();
  1001. });
  1002. stop_tracing.Run();
  1003. system_data_source_disabled_runloop.Run();
  1004. system_no_more_packets_runloop.Run();
  1005. system_consumer.WaitForAllDataSourcesStopped();
  1006. if (saved_producer_sock_name) {
  1007. ASSERT_EQ(0, setenv(kProducerSockEnvName, saved_producer_sock_name, true));
  1008. } else {
  1009. ASSERT_EQ(0, unsetenv(kProducerSockEnvName));
  1010. }
  1011. EXPECT_EQ(1u, system_consumer.received_test_packets());
  1012. PerfettoProducer::DeleteSoonForTesting(std::move(system_producer));
  1013. }
  1014. #endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
  1015. } // namespace
  1016. } // namespace tracing