file_metrics_provider_unittest.cc 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. // Copyright 2016 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 "components/metrics/file_metrics_provider.h"
  5. #include <memory>
  6. #include "base/bind.h"
  7. #include "base/callback.h"
  8. #include "base/files/file_util.h"
  9. #include "base/files/memory_mapped_file.h"
  10. #include "base/files/scoped_temp_dir.h"
  11. #include "base/logging.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/metrics/histogram.h"
  14. #include "base/metrics/histogram_flattener.h"
  15. #include "base/metrics/histogram_snapshot_manager.h"
  16. #include "base/metrics/persistent_histogram_allocator.h"
  17. #include "base/metrics/persistent_memory_allocator.h"
  18. #include "base/metrics/sparse_histogram.h"
  19. #include "base/metrics/statistics_recorder.h"
  20. #include "base/strings/stringprintf.h"
  21. #include "base/synchronization/waitable_event.h"
  22. #include "base/test/test_simple_task_runner.h"
  23. #include "base/threading/thread_task_runner_handle.h"
  24. #include "base/time/time.h"
  25. #include "components/metrics/metrics_pref_names.h"
  26. #include "components/metrics/persistent_system_profile.h"
  27. #include "components/prefs/pref_registry_simple.h"
  28. #include "components/prefs/testing_pref_service.h"
  29. #include "testing/gtest/include/gtest/gtest.h"
  30. #include "third_party/metrics_proto/chrome_user_metrics_extension.pb.h"
  31. #include "third_party/metrics_proto/system_profile.pb.h"
  32. namespace {
  33. const char kMetricsName[] = "TestMetrics";
  34. const char kMetricsFilename[] = "file.metrics";
  35. } // namespace
  36. namespace metrics {
  37. class HistogramFlattenerDeltaRecorder : public base::HistogramFlattener {
  38. public:
  39. HistogramFlattenerDeltaRecorder() {}
  40. HistogramFlattenerDeltaRecorder(const HistogramFlattenerDeltaRecorder&) =
  41. delete;
  42. HistogramFlattenerDeltaRecorder& operator=(
  43. const HistogramFlattenerDeltaRecorder&) = delete;
  44. void RecordDelta(const base::HistogramBase& histogram,
  45. const base::HistogramSamples& snapshot) override {
  46. // Only remember locally created histograms; they have exactly 2 chars.
  47. if (strlen(histogram.histogram_name()) == 2)
  48. recorded_delta_histogram_names_.push_back(histogram.histogram_name());
  49. }
  50. std::vector<std::string> GetRecordedDeltaHistogramNames() {
  51. return recorded_delta_histogram_names_;
  52. }
  53. private:
  54. std::vector<std::string> recorded_delta_histogram_names_;
  55. };
  56. class FileMetricsProviderTest : public testing::TestWithParam<bool> {
  57. public:
  58. FileMetricsProviderTest(const FileMetricsProviderTest&) = delete;
  59. FileMetricsProviderTest& operator=(const FileMetricsProviderTest&) = delete;
  60. protected:
  61. const size_t kSmallFileSize = 64 << 10; // 64 KiB
  62. const size_t kLargeFileSize = 2 << 20; // 2 MiB
  63. enum : int { kMaxCreateHistograms = 10 };
  64. FileMetricsProviderTest()
  65. : create_large_files_(GetParam()),
  66. task_runner_(new base::TestSimpleTaskRunner()),
  67. thread_task_runner_handle_(task_runner_),
  68. statistics_recorder_(
  69. base::StatisticsRecorder::CreateTemporaryForTesting()),
  70. prefs_(new TestingPrefServiceSimple) {
  71. EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
  72. FileMetricsProvider::RegisterSourcePrefs(prefs_->registry(), kMetricsName);
  73. FileMetricsProvider::SetTaskRunnerForTesting(task_runner_);
  74. }
  75. ~FileMetricsProviderTest() override {
  76. // Clear out any final remaining tasks.
  77. task_runner_->RunUntilIdle();
  78. FileMetricsProvider::SetTaskRunnerForTesting(nullptr);
  79. DCHECK_EQ(0U, filter_actions_remaining_);
  80. // If a global histogram allocator exists at this point then it likely
  81. // acquired histograms that will continue to point to the released
  82. // memory and potentially cause use-after-free memory corruption.
  83. DCHECK(!base::GlobalHistogramAllocator::Get());
  84. }
  85. TestingPrefServiceSimple* prefs() { return prefs_.get(); }
  86. base::FilePath temp_dir() { return temp_dir_.GetPath(); }
  87. base::FilePath metrics_file() {
  88. return temp_dir_.GetPath().AppendASCII(kMetricsFilename);
  89. }
  90. FileMetricsProvider* provider() {
  91. if (!provider_)
  92. provider_ = std::make_unique<FileMetricsProvider>(prefs());
  93. return provider_.get();
  94. }
  95. void OnDidCreateMetricsLog() {
  96. provider()->OnDidCreateMetricsLog();
  97. }
  98. bool HasPreviousSessionData() { return provider()->HasPreviousSessionData(); }
  99. void MergeHistogramDeltas() {
  100. provider()->MergeHistogramDeltas();
  101. }
  102. bool HasIndependentMetrics() { return provider()->HasIndependentMetrics(); }
  103. bool ProvideIndependentMetrics(
  104. ChromeUserMetricsExtension* uma_proto,
  105. base::HistogramSnapshotManager* snapshot_manager) {
  106. bool success = false;
  107. bool success_set = false;
  108. provider()->ProvideIndependentMetrics(
  109. base::BindOnce(
  110. [](bool* success_ptr, bool* set_ptr, bool s) {
  111. *success_ptr = s;
  112. *set_ptr = true;
  113. },
  114. &success, &success_set),
  115. uma_proto, snapshot_manager);
  116. RunTasks();
  117. CHECK(success_set);
  118. return success;
  119. }
  120. void RecordInitialHistogramSnapshots(
  121. base::HistogramSnapshotManager* snapshot_manager) {
  122. provider()->RecordInitialHistogramSnapshots(snapshot_manager);
  123. }
  124. size_t GetSnapshotHistogramCount() {
  125. // Merge the data from the allocator into the StatisticsRecorder.
  126. provider()->MergeHistogramDeltas();
  127. // Flatten what is known to see what has changed since the last time.
  128. HistogramFlattenerDeltaRecorder flattener;
  129. base::HistogramSnapshotManager snapshot_manager(&flattener);
  130. // "true" to the begin() includes histograms held in persistent storage.
  131. base::StatisticsRecorder::PrepareDeltas(true, base::Histogram::kNoFlags,
  132. base::Histogram::kNoFlags,
  133. &snapshot_manager);
  134. return flattener.GetRecordedDeltaHistogramNames().size();
  135. }
  136. size_t GetIndependentHistogramCount() {
  137. HistogramFlattenerDeltaRecorder flattener;
  138. base::HistogramSnapshotManager snapshot_manager(&flattener);
  139. ChromeUserMetricsExtension uma_proto;
  140. provider()->ProvideIndependentMetrics(base::BindOnce([](bool success) {}),
  141. &uma_proto, &snapshot_manager);
  142. RunTasks();
  143. return flattener.GetRecordedDeltaHistogramNames().size();
  144. }
  145. void CreateGlobalHistograms(int histogram_count) {
  146. DCHECK_GT(kMaxCreateHistograms, histogram_count);
  147. // Create both sparse and normal histograms in the allocator.
  148. created_histograms_[0] = base::SparseHistogram::FactoryGet("h0", 0);
  149. created_histograms_[0]->Add(0);
  150. for (int i = 1; i < histogram_count; ++i) {
  151. created_histograms_[i] = base::Histogram::FactoryGet(
  152. base::StringPrintf("h%d", i), 1, 100, 10, 0);
  153. created_histograms_[i]->Add(i);
  154. }
  155. }
  156. void RunTasks() {
  157. // Run pending tasks twice: Once for IPC calls, once for replies. Don't
  158. // use RunUntilIdle() because that can do more work than desired.
  159. task_runner_->RunPendingTasks();
  160. task_runner_->RunPendingTasks();
  161. }
  162. void WriteMetricsFile(const base::FilePath& path,
  163. base::PersistentHistogramAllocator* metrics) {
  164. base::File writer(path,
  165. base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
  166. // Use DCHECK so the stack-trace will indicate where this was called.
  167. DCHECK(writer.IsValid()) << path.value();
  168. size_t file_size = create_large_files_ ? metrics->size() : metrics->used();
  169. int written = writer.Write(0, (const char*)metrics->data(), file_size);
  170. DCHECK_EQ(static_cast<int>(file_size), written);
  171. }
  172. void WriteMetricsFileAtTime(const base::FilePath& path,
  173. base::PersistentHistogramAllocator* metrics,
  174. base::Time write_time) {
  175. WriteMetricsFile(path, metrics);
  176. base::TouchFile(path, write_time, write_time);
  177. }
  178. std::unique_ptr<base::PersistentHistogramAllocator>
  179. CreateMetricsFileWithHistograms(
  180. const base::FilePath& file_path,
  181. base::Time write_time,
  182. int histogram_count,
  183. base::OnceCallback<void(base::PersistentHistogramAllocator*)> callback) {
  184. base::GlobalHistogramAllocator::CreateWithLocalMemory(
  185. create_large_files_ ? kLargeFileSize : kSmallFileSize,
  186. 0, kMetricsName);
  187. CreateGlobalHistograms(histogram_count);
  188. std::unique_ptr<base::PersistentHistogramAllocator> histogram_allocator =
  189. base::GlobalHistogramAllocator::ReleaseForTesting();
  190. std::move(callback).Run(histogram_allocator.get());
  191. WriteMetricsFileAtTime(file_path, histogram_allocator.get(), write_time);
  192. return histogram_allocator;
  193. }
  194. std::unique_ptr<base::PersistentHistogramAllocator>
  195. CreateMetricsFileWithHistograms(int histogram_count) {
  196. return CreateMetricsFileWithHistograms(
  197. metrics_file(), base::Time::Now(), histogram_count,
  198. base::BindOnce([](base::PersistentHistogramAllocator* allocator) {}));
  199. }
  200. base::HistogramBase* GetCreatedHistogram(int index) {
  201. DCHECK_GT(kMaxCreateHistograms, index);
  202. return created_histograms_[index];
  203. }
  204. void SetFilterActions(FileMetricsProvider::Params* params,
  205. const FileMetricsProvider::FilterAction* actions,
  206. size_t count) {
  207. filter_actions_ = actions;
  208. filter_actions_remaining_ = count;
  209. params->filter = base::BindRepeating(
  210. &FileMetricsProviderTest::FilterSourcePath, base::Unretained(this));
  211. }
  212. const bool create_large_files_;
  213. private:
  214. FileMetricsProvider::FilterAction FilterSourcePath(
  215. const base::FilePath& path) {
  216. DCHECK_LT(0U, filter_actions_remaining_);
  217. --filter_actions_remaining_;
  218. return *filter_actions_++;
  219. }
  220. scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
  221. base::ThreadTaskRunnerHandle thread_task_runner_handle_;
  222. std::unique_ptr<base::StatisticsRecorder> statistics_recorder_;
  223. base::ScopedTempDir temp_dir_;
  224. std::unique_ptr<TestingPrefServiceSimple> prefs_;
  225. std::unique_ptr<FileMetricsProvider> provider_;
  226. base::HistogramBase* created_histograms_[kMaxCreateHistograms];
  227. raw_ptr<const FileMetricsProvider::FilterAction> filter_actions_ = nullptr;
  228. size_t filter_actions_remaining_ = 0;
  229. };
  230. // Run all test cases with both small and large files.
  231. INSTANTIATE_TEST_SUITE_P(SmallAndLargeFiles,
  232. FileMetricsProviderTest,
  233. testing::Bool());
  234. TEST_P(FileMetricsProviderTest, AccessMetrics) {
  235. ASSERT_FALSE(PathExists(metrics_file()));
  236. base::Time metrics_time = base::Time::Now() - base::Minutes(5);
  237. std::unique_ptr<base::PersistentHistogramAllocator> histogram_allocator =
  238. CreateMetricsFileWithHistograms(2);
  239. ASSERT_TRUE(PathExists(metrics_file()));
  240. base::TouchFile(metrics_file(), metrics_time, metrics_time);
  241. // Register the file and allow the "checker" task to run.
  242. provider()->RegisterSource(FileMetricsProvider::Params(
  243. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_FILE,
  244. FileMetricsProvider::ASSOCIATE_CURRENT_RUN, kMetricsName));
  245. // Record embedded snapshots via snapshot-manager.
  246. OnDidCreateMetricsLog();
  247. RunTasks();
  248. EXPECT_EQ(2U, GetSnapshotHistogramCount());
  249. EXPECT_FALSE(base::PathExists(metrics_file()));
  250. // Make sure a second call to the snapshot-recorder doesn't break anything.
  251. OnDidCreateMetricsLog();
  252. RunTasks();
  253. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  254. // File should have been deleted but recreate it to test behavior should
  255. // the file not be deleteable by this process.
  256. WriteMetricsFileAtTime(metrics_file(), histogram_allocator.get(),
  257. metrics_time);
  258. // Second full run on the same file should produce nothing.
  259. OnDidCreateMetricsLog();
  260. RunTasks();
  261. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  262. EXPECT_FALSE(base::PathExists(metrics_file()));
  263. // Recreate the file to indicate that it is "new" and must be recorded.
  264. metrics_time = metrics_time + base::Minutes(1);
  265. WriteMetricsFileAtTime(metrics_file(), histogram_allocator.get(),
  266. metrics_time);
  267. // This run should again have "new" histograms.
  268. OnDidCreateMetricsLog();
  269. RunTasks();
  270. EXPECT_EQ(2U, GetSnapshotHistogramCount());
  271. EXPECT_FALSE(base::PathExists(metrics_file()));
  272. }
  273. TEST_P(FileMetricsProviderTest, AccessTimeLimitedFile) {
  274. ASSERT_FALSE(PathExists(metrics_file()));
  275. base::Time metrics_time = base::Time::Now() - base::Hours(5);
  276. std::unique_ptr<base::PersistentHistogramAllocator> histogram_allocator =
  277. CreateMetricsFileWithHistograms(2);
  278. ASSERT_TRUE(PathExists(metrics_file()));
  279. base::TouchFile(metrics_file(), metrics_time, metrics_time);
  280. // Register the file and allow the "checker" task to run.
  281. FileMetricsProvider::Params params(
  282. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_FILE,
  283. FileMetricsProvider::ASSOCIATE_CURRENT_RUN, kMetricsName);
  284. params.max_age = base::Hours(1);
  285. provider()->RegisterSource(params);
  286. // Attempt to access the file should return nothing.
  287. OnDidCreateMetricsLog();
  288. RunTasks();
  289. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  290. EXPECT_FALSE(base::PathExists(metrics_file()));
  291. }
  292. TEST_P(FileMetricsProviderTest, FilterDelaysFile) {
  293. ASSERT_FALSE(PathExists(metrics_file()));
  294. base::Time now_time = base::Time::Now();
  295. base::Time metrics_time = now_time - base::Minutes(5);
  296. std::unique_ptr<base::PersistentHistogramAllocator> histogram_allocator =
  297. CreateMetricsFileWithHistograms(2);
  298. ASSERT_TRUE(PathExists(metrics_file()));
  299. base::TouchFile(metrics_file(), metrics_time, metrics_time);
  300. base::File::Info fileinfo;
  301. ASSERT_TRUE(base::GetFileInfo(metrics_file(), &fileinfo));
  302. EXPECT_GT(base::Time::Now(), fileinfo.last_modified);
  303. // Register the file and allow the "checker" task to run.
  304. FileMetricsProvider::Params params(
  305. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_FILE,
  306. FileMetricsProvider::ASSOCIATE_CURRENT_RUN, kMetricsName);
  307. const FileMetricsProvider::FilterAction actions[] = {
  308. FileMetricsProvider::FILTER_TRY_LATER,
  309. FileMetricsProvider::FILTER_PROCESS_FILE};
  310. SetFilterActions(&params, actions, std::size(actions));
  311. provider()->RegisterSource(params);
  312. // Processing the file should touch it but yield no results. File timestamp
  313. // accuracy is limited so compare the touched time to a couple seconds past.
  314. OnDidCreateMetricsLog();
  315. RunTasks();
  316. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  317. EXPECT_TRUE(base::PathExists(metrics_file()));
  318. ASSERT_TRUE(base::GetFileInfo(metrics_file(), &fileinfo));
  319. EXPECT_LT(metrics_time, fileinfo.last_modified);
  320. EXPECT_LE(now_time - base::Seconds(2), fileinfo.last_modified);
  321. // Second full run on the same file should process the file.
  322. OnDidCreateMetricsLog();
  323. RunTasks();
  324. EXPECT_EQ(2U, GetSnapshotHistogramCount());
  325. EXPECT_FALSE(base::PathExists(metrics_file()));
  326. }
  327. TEST_P(FileMetricsProviderTest, FilterSkipsFile) {
  328. ASSERT_FALSE(PathExists(metrics_file()));
  329. base::Time now_time = base::Time::Now();
  330. base::Time metrics_time = now_time - base::Minutes(5);
  331. std::unique_ptr<base::PersistentHistogramAllocator> histogram_allocator =
  332. CreateMetricsFileWithHistograms(2);
  333. ASSERT_TRUE(PathExists(metrics_file()));
  334. base::TouchFile(metrics_file(), metrics_time, metrics_time);
  335. base::File::Info fileinfo;
  336. ASSERT_TRUE(base::GetFileInfo(metrics_file(), &fileinfo));
  337. EXPECT_GT(base::Time::Now(), fileinfo.last_modified);
  338. // Register the file and allow the "checker" task to run.
  339. FileMetricsProvider::Params params(
  340. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_FILE,
  341. FileMetricsProvider::ASSOCIATE_CURRENT_RUN, kMetricsName);
  342. const FileMetricsProvider::FilterAction actions[] = {
  343. FileMetricsProvider::FILTER_SKIP_FILE};
  344. SetFilterActions(&params, actions, std::size(actions));
  345. provider()->RegisterSource(params);
  346. // Processing the file should delete it.
  347. OnDidCreateMetricsLog();
  348. RunTasks();
  349. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  350. EXPECT_FALSE(base::PathExists(metrics_file()));
  351. }
  352. TEST_P(FileMetricsProviderTest, AccessDirectory) {
  353. ASSERT_FALSE(PathExists(metrics_file()));
  354. base::GlobalHistogramAllocator::CreateWithLocalMemory(
  355. 64 << 10, 0, kMetricsName);
  356. base::GlobalHistogramAllocator* allocator =
  357. base::GlobalHistogramAllocator::Get();
  358. base::HistogramBase* histogram;
  359. // Create files starting with a timestamp a few minutes back.
  360. base::Time base_time = base::Time::Now() - base::Minutes(10);
  361. // Create some files in an odd order. The files are "touched" back in time to
  362. // ensure that each file has a later timestamp on disk than the previous one.
  363. base::ScopedTempDir metrics_files;
  364. EXPECT_TRUE(metrics_files.CreateUniqueTempDir());
  365. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII(".foo.pma"),
  366. allocator, base_time);
  367. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("_bar.pma"),
  368. allocator, base_time);
  369. histogram = base::Histogram::FactoryGet("h1", 1, 100, 10, 0);
  370. histogram->Add(1);
  371. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("a1.pma"),
  372. allocator, base_time + base::Minutes(1));
  373. histogram = base::Histogram::FactoryGet("h2", 1, 100, 10, 0);
  374. histogram->Add(2);
  375. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("c2.pma"),
  376. allocator, base_time + base::Minutes(2));
  377. histogram = base::Histogram::FactoryGet("h3", 1, 100, 10, 0);
  378. histogram->Add(3);
  379. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("b3.pma"),
  380. allocator, base_time + base::Minutes(3));
  381. histogram = base::Histogram::FactoryGet("h4", 1, 100, 10, 0);
  382. histogram->Add(3);
  383. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("d4.pma"),
  384. allocator, base_time + base::Minutes(4));
  385. base::TouchFile(metrics_files.GetPath().AppendASCII("b3.pma"),
  386. base_time + base::Minutes(5), base_time + base::Minutes(5));
  387. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("baz"), allocator,
  388. base_time + base::Minutes(6));
  389. // The global allocator has to be detached here so that no metrics created
  390. // by code called below get stored in it as that would make for potential
  391. // use-after-free operations if that code is called again.
  392. base::GlobalHistogramAllocator::ReleaseForTesting();
  393. // Register the file and allow the "checker" task to run.
  394. provider()->RegisterSource(FileMetricsProvider::Params(
  395. metrics_files.GetPath(),
  396. FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_DIR,
  397. FileMetricsProvider::ASSOCIATE_CURRENT_RUN, kMetricsName));
  398. // Files could come out in the order: a1, c2, d4, b3. They are recognizeable
  399. // by the number of histograms contained within each.
  400. const uint32_t expect_order[] = {1, 2, 4, 3, 0};
  401. for (size_t i = 0; i < std::size(expect_order); ++i) {
  402. // Record embedded snapshots via snapshot-manager.
  403. OnDidCreateMetricsLog();
  404. RunTasks();
  405. EXPECT_EQ(expect_order[i], GetSnapshotHistogramCount()) << i;
  406. }
  407. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("a1.pma")));
  408. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("c2.pma")));
  409. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("b3.pma")));
  410. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("d4.pma")));
  411. EXPECT_TRUE(
  412. base::PathExists(metrics_files.GetPath().AppendASCII(".foo.pma")));
  413. EXPECT_TRUE(
  414. base::PathExists(metrics_files.GetPath().AppendASCII("_bar.pma")));
  415. EXPECT_TRUE(base::PathExists(metrics_files.GetPath().AppendASCII("baz")));
  416. }
  417. TEST_P(FileMetricsProviderTest, AccessDirectoryWithInvalidFiles) {
  418. ASSERT_FALSE(PathExists(metrics_file()));
  419. // Create files starting with a timestamp a few minutes back.
  420. base::Time base_time = base::Time::Now() - base::Minutes(10);
  421. base::ScopedTempDir metrics_files;
  422. EXPECT_TRUE(metrics_files.CreateUniqueTempDir());
  423. CreateMetricsFileWithHistograms(
  424. metrics_files.GetPath().AppendASCII("h1.pma"),
  425. base_time + base::Minutes(1), 1,
  426. base::BindOnce([](base::PersistentHistogramAllocator* allocator) {
  427. allocator->memory_allocator()->SetMemoryState(
  428. base::PersistentMemoryAllocator::MEMORY_DELETED);
  429. }));
  430. CreateMetricsFileWithHistograms(
  431. metrics_files.GetPath().AppendASCII("h2.pma"),
  432. base_time + base::Minutes(2), 2,
  433. base::BindOnce([](base::PersistentHistogramAllocator* allocator) {
  434. SystemProfileProto profile_proto;
  435. SystemProfileProto::FieldTrial* trial = profile_proto.add_field_trial();
  436. trial->set_name_id(123);
  437. trial->set_group_id(456);
  438. PersistentSystemProfile persistent_profile;
  439. persistent_profile.RegisterPersistentAllocator(
  440. allocator->memory_allocator());
  441. persistent_profile.SetSystemProfile(profile_proto, true);
  442. }));
  443. CreateMetricsFileWithHistograms(
  444. metrics_files.GetPath().AppendASCII("h3.pma"),
  445. base_time + base::Minutes(3), 3,
  446. base::BindOnce([](base::PersistentHistogramAllocator* allocator) {
  447. allocator->memory_allocator()->SetMemoryState(
  448. base::PersistentMemoryAllocator::MEMORY_DELETED);
  449. }));
  450. {
  451. base::File empty(metrics_files.GetPath().AppendASCII("h4.pma"),
  452. base::File::FLAG_CREATE | base::File::FLAG_WRITE);
  453. }
  454. base::TouchFile(metrics_files.GetPath().AppendASCII("h4.pma"),
  455. base_time + base::Minutes(4), base_time + base::Minutes(4));
  456. // Register the file and allow the "checker" task to run.
  457. provider()->RegisterSource(FileMetricsProvider::Params(
  458. metrics_files.GetPath(),
  459. FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_DIR,
  460. FileMetricsProvider::ASSOCIATE_INTERNAL_PROFILE, kMetricsName));
  461. // No files yet.
  462. EXPECT_EQ(0U, GetIndependentHistogramCount());
  463. EXPECT_TRUE(base::PathExists(metrics_files.GetPath().AppendASCII("h1.pma")));
  464. EXPECT_TRUE(base::PathExists(metrics_files.GetPath().AppendASCII("h2.pma")));
  465. EXPECT_TRUE(base::PathExists(metrics_files.GetPath().AppendASCII("h3.pma")));
  466. EXPECT_TRUE(base::PathExists(metrics_files.GetPath().AppendASCII("h4.pma")));
  467. // H1 should be skipped and H2 available.
  468. OnDidCreateMetricsLog();
  469. RunTasks();
  470. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("h1.pma")));
  471. EXPECT_TRUE(base::PathExists(metrics_files.GetPath().AppendASCII("h2.pma")));
  472. EXPECT_TRUE(base::PathExists(metrics_files.GetPath().AppendASCII("h3.pma")));
  473. EXPECT_TRUE(base::PathExists(metrics_files.GetPath().AppendASCII("h4.pma")));
  474. // H2 should be read and the file deleted.
  475. EXPECT_EQ(2U, GetIndependentHistogramCount());
  476. RunTasks();
  477. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("h2.pma")));
  478. // Nothing else should be found but the last (valid but empty) file will
  479. // stick around to be processed later (should it get expanded).
  480. EXPECT_EQ(0U, GetIndependentHistogramCount());
  481. RunTasks();
  482. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("h3.pma")));
  483. EXPECT_TRUE(base::PathExists(metrics_files.GetPath().AppendASCII("h4.pma")));
  484. }
  485. TEST_P(FileMetricsProviderTest, AccessTimeLimitedDirectory) {
  486. ASSERT_FALSE(PathExists(metrics_file()));
  487. base::GlobalHistogramAllocator::CreateWithLocalMemory(64 << 10, 0,
  488. kMetricsName);
  489. base::GlobalHistogramAllocator* allocator =
  490. base::GlobalHistogramAllocator::Get();
  491. base::HistogramBase* histogram;
  492. // Create one old file and one new file.
  493. base::ScopedTempDir metrics_files;
  494. EXPECT_TRUE(metrics_files.CreateUniqueTempDir());
  495. histogram = base::Histogram::FactoryGet("h1", 1, 100, 10, 0);
  496. histogram->Add(1);
  497. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("a1.pma"),
  498. allocator, base::Time::Now() - base::Hours(1));
  499. histogram = base::Histogram::FactoryGet("h2", 1, 100, 10, 0);
  500. histogram->Add(2);
  501. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("b2.pma"),
  502. allocator, base::Time::Now());
  503. // The global allocator has to be detached here so that no metrics created
  504. // by code called below get stored in it as that would make for potential
  505. // use-after-free operations if that code is called again.
  506. base::GlobalHistogramAllocator::ReleaseForTesting();
  507. // Register the file and allow the "checker" task to run.
  508. FileMetricsProvider::Params params(
  509. metrics_files.GetPath(),
  510. FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_DIR,
  511. FileMetricsProvider::ASSOCIATE_CURRENT_RUN, kMetricsName);
  512. params.max_age = base::Minutes(30);
  513. provider()->RegisterSource(params);
  514. // Only b2, with 2 histograms, should be read.
  515. OnDidCreateMetricsLog();
  516. RunTasks();
  517. EXPECT_EQ(2U, GetSnapshotHistogramCount());
  518. OnDidCreateMetricsLog();
  519. RunTasks();
  520. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  521. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("a1.pma")));
  522. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("b2.pma")));
  523. }
  524. TEST_P(FileMetricsProviderTest, AccessCountLimitedDirectory) {
  525. ASSERT_FALSE(PathExists(metrics_file()));
  526. base::GlobalHistogramAllocator::CreateWithLocalMemory(64 << 10, 0,
  527. kMetricsName);
  528. base::GlobalHistogramAllocator* allocator =
  529. base::GlobalHistogramAllocator::Get();
  530. base::HistogramBase* histogram;
  531. // Create one old file and one new file.
  532. base::ScopedTempDir metrics_files;
  533. EXPECT_TRUE(metrics_files.CreateUniqueTempDir());
  534. histogram = base::Histogram::FactoryGet("h1", 1, 100, 10, 0);
  535. histogram->Add(1);
  536. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("a1.pma"),
  537. allocator, base::Time::Now() - base::Hours(1));
  538. histogram = base::Histogram::FactoryGet("h2", 1, 100, 10, 0);
  539. histogram->Add(2);
  540. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("b2.pma"),
  541. allocator, base::Time::Now());
  542. // The global allocator has to be detached here so that no metrics created
  543. // by code called below get stored in it as that would make for potential
  544. // use-after-free operations if that code is called again.
  545. base::GlobalHistogramAllocator::ReleaseForTesting();
  546. // Register the file and allow the "checker" task to run.
  547. FileMetricsProvider::Params params(
  548. metrics_files.GetPath(),
  549. FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_DIR,
  550. FileMetricsProvider::ASSOCIATE_CURRENT_RUN, kMetricsName);
  551. params.max_dir_files = 1;
  552. provider()->RegisterSource(params);
  553. // Only b2, with 2 histograms, should be read.
  554. OnDidCreateMetricsLog();
  555. RunTasks();
  556. EXPECT_EQ(2U, GetSnapshotHistogramCount());
  557. OnDidCreateMetricsLog();
  558. RunTasks();
  559. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  560. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("a1.pma")));
  561. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("b2.pma")));
  562. }
  563. TEST_P(FileMetricsProviderTest, AccessSizeLimitedDirectory) {
  564. // This only works with large files that are big enough to count.
  565. if (!create_large_files_)
  566. return;
  567. ASSERT_FALSE(PathExists(metrics_file()));
  568. size_t file_size_kib = 64;
  569. base::GlobalHistogramAllocator::CreateWithLocalMemory(file_size_kib << 10, 0,
  570. kMetricsName);
  571. base::GlobalHistogramAllocator* allocator =
  572. base::GlobalHistogramAllocator::Get();
  573. base::HistogramBase* histogram;
  574. // Create one old file and one new file.
  575. base::ScopedTempDir metrics_files;
  576. EXPECT_TRUE(metrics_files.CreateUniqueTempDir());
  577. histogram = base::Histogram::FactoryGet("h1", 1, 100, 10, 0);
  578. histogram->Add(1);
  579. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("a1.pma"),
  580. allocator, base::Time::Now() - base::Hours(1));
  581. histogram = base::Histogram::FactoryGet("h2", 1, 100, 10, 0);
  582. histogram->Add(2);
  583. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("b2.pma"),
  584. allocator, base::Time::Now());
  585. // The global allocator has to be detached here so that no metrics created
  586. // by code called below get stored in it as that would make for potential
  587. // use-after-free operations if that code is called again.
  588. base::GlobalHistogramAllocator::ReleaseForTesting();
  589. // Register the file and allow the "checker" task to run.
  590. FileMetricsProvider::Params params(
  591. metrics_files.GetPath(),
  592. FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_DIR,
  593. FileMetricsProvider::ASSOCIATE_CURRENT_RUN, kMetricsName);
  594. params.max_dir_kib = file_size_kib + 1;
  595. provider()->RegisterSource(params);
  596. // Only b2, with 2 histograms, should be read.
  597. OnDidCreateMetricsLog();
  598. RunTasks();
  599. EXPECT_EQ(2U, GetSnapshotHistogramCount());
  600. OnDidCreateMetricsLog();
  601. RunTasks();
  602. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  603. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("a1.pma")));
  604. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("b2.pma")));
  605. }
  606. TEST_P(FileMetricsProviderTest, AccessFilteredDirectory) {
  607. ASSERT_FALSE(PathExists(metrics_file()));
  608. base::GlobalHistogramAllocator::CreateWithLocalMemory(64 << 10, 0,
  609. kMetricsName);
  610. base::GlobalHistogramAllocator* allocator =
  611. base::GlobalHistogramAllocator::Get();
  612. base::HistogramBase* histogram;
  613. // Create files starting with a timestamp a few minutes back.
  614. base::Time base_time = base::Time::Now() - base::Minutes(10);
  615. // Create some files in an odd order. The files are "touched" back in time to
  616. // ensure that each file has a later timestamp on disk than the previous one.
  617. base::ScopedTempDir metrics_files;
  618. EXPECT_TRUE(metrics_files.CreateUniqueTempDir());
  619. histogram = base::Histogram::FactoryGet("h1", 1, 100, 10, 0);
  620. histogram->Add(1);
  621. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("a1.pma"),
  622. allocator, base_time + base::Minutes(1));
  623. histogram = base::Histogram::FactoryGet("h2", 1, 100, 10, 0);
  624. histogram->Add(2);
  625. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("c2.pma"),
  626. allocator, base_time + base::Minutes(2));
  627. histogram = base::Histogram::FactoryGet("h3", 1, 100, 10, 0);
  628. histogram->Add(3);
  629. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("b3.pma"),
  630. allocator, base_time + base::Minutes(3));
  631. histogram = base::Histogram::FactoryGet("h4", 1, 100, 10, 0);
  632. histogram->Add(3);
  633. WriteMetricsFileAtTime(metrics_files.GetPath().AppendASCII("d4.pma"),
  634. allocator, base_time + base::Minutes(4));
  635. base::TouchFile(metrics_files.GetPath().AppendASCII("b3.pma"),
  636. base_time + base::Minutes(5), base_time + base::Minutes(5));
  637. // The global allocator has to be detached here so that no metrics created
  638. // by code called below get stored in it as that would make for potential
  639. // use-after-free operations if that code is called again.
  640. base::GlobalHistogramAllocator::ReleaseForTesting();
  641. // Register the file and allow the "checker" task to run.
  642. FileMetricsProvider::Params params(
  643. metrics_files.GetPath(),
  644. FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_DIR,
  645. FileMetricsProvider::ASSOCIATE_CURRENT_RUN, kMetricsName);
  646. const FileMetricsProvider::FilterAction actions[] = {
  647. FileMetricsProvider::FILTER_PROCESS_FILE, // a1
  648. FileMetricsProvider::FILTER_TRY_LATER, // c2
  649. FileMetricsProvider::FILTER_SKIP_FILE, // d4
  650. FileMetricsProvider::FILTER_PROCESS_FILE, // b3
  651. FileMetricsProvider::FILTER_PROCESS_FILE}; // c2 (again)
  652. SetFilterActions(&params, actions, std::size(actions));
  653. provider()->RegisterSource(params);
  654. // Files could come out in the order: a1, b3, c2. They are recognizeable
  655. // by the number of histograms contained within each.
  656. const uint32_t expect_order[] = {1, 3, 2, 0};
  657. for (size_t i = 0; i < std::size(expect_order); ++i) {
  658. // Record embedded snapshots via snapshot-manager.
  659. OnDidCreateMetricsLog();
  660. RunTasks();
  661. EXPECT_EQ(expect_order[i], GetSnapshotHistogramCount()) << i;
  662. }
  663. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("a1.pma")));
  664. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("c2.pma")));
  665. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("b3.pma")));
  666. EXPECT_FALSE(base::PathExists(metrics_files.GetPath().AppendASCII("d4.pma")));
  667. }
  668. TEST_P(FileMetricsProviderTest, AccessReadWriteMetrics) {
  669. // Create a global histogram allocator that maps to a file.
  670. ASSERT_FALSE(PathExists(metrics_file()));
  671. base::GlobalHistogramAllocator::CreateWithFile(
  672. metrics_file(),
  673. create_large_files_ ? kLargeFileSize : kSmallFileSize,
  674. 0, kMetricsName);
  675. CreateGlobalHistograms(2);
  676. ASSERT_TRUE(PathExists(metrics_file()));
  677. base::HistogramBase* h0 = GetCreatedHistogram(0);
  678. base::HistogramBase* h1 = GetCreatedHistogram(1);
  679. DCHECK(h0);
  680. DCHECK(h1);
  681. std::unique_ptr<base::PersistentHistogramAllocator> histogram_allocator =
  682. base::GlobalHistogramAllocator::ReleaseForTesting();
  683. // Register the file and allow the "checker" task to run.
  684. provider()->RegisterSource(FileMetricsProvider::Params(
  685. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ACTIVE_FILE,
  686. FileMetricsProvider::ASSOCIATE_CURRENT_RUN));
  687. // Record embedded snapshots via snapshot-manager.
  688. OnDidCreateMetricsLog();
  689. RunTasks();
  690. EXPECT_EQ(2U, GetSnapshotHistogramCount());
  691. EXPECT_TRUE(base::PathExists(metrics_file()));
  692. // Make sure a second call to the snapshot-recorder doesn't break anything.
  693. OnDidCreateMetricsLog();
  694. RunTasks();
  695. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  696. EXPECT_TRUE(base::PathExists(metrics_file()));
  697. // Change a histogram and ensure that it's counted.
  698. h0->Add(0);
  699. EXPECT_EQ(1U, GetSnapshotHistogramCount());
  700. EXPECT_TRUE(base::PathExists(metrics_file()));
  701. // Change the other histogram and verify.
  702. h1->Add(11);
  703. EXPECT_EQ(1U, GetSnapshotHistogramCount());
  704. EXPECT_TRUE(base::PathExists(metrics_file()));
  705. }
  706. TEST_P(FileMetricsProviderTest, AccessInitialMetrics) {
  707. ASSERT_FALSE(PathExists(metrics_file()));
  708. CreateMetricsFileWithHistograms(2);
  709. // Register the file and allow the "checker" task to run.
  710. ASSERT_TRUE(PathExists(metrics_file()));
  711. provider()->RegisterSource(FileMetricsProvider::Params(
  712. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_FILE,
  713. FileMetricsProvider::ASSOCIATE_PREVIOUS_RUN, kMetricsName));
  714. // Record embedded snapshots via snapshot-manager.
  715. ASSERT_TRUE(HasPreviousSessionData());
  716. RunTasks();
  717. {
  718. HistogramFlattenerDeltaRecorder flattener;
  719. base::HistogramSnapshotManager snapshot_manager(&flattener);
  720. RecordInitialHistogramSnapshots(&snapshot_manager);
  721. EXPECT_EQ(2U, flattener.GetRecordedDeltaHistogramNames().size());
  722. }
  723. EXPECT_TRUE(base::PathExists(metrics_file()));
  724. OnDidCreateMetricsLog();
  725. RunTasks();
  726. EXPECT_FALSE(base::PathExists(metrics_file()));
  727. // A run for normal histograms should produce nothing.
  728. CreateMetricsFileWithHistograms(2);
  729. OnDidCreateMetricsLog();
  730. RunTasks();
  731. EXPECT_EQ(0U, GetSnapshotHistogramCount());
  732. EXPECT_TRUE(base::PathExists(metrics_file()));
  733. OnDidCreateMetricsLog();
  734. RunTasks();
  735. EXPECT_TRUE(base::PathExists(metrics_file()));
  736. }
  737. TEST_P(FileMetricsProviderTest, AccessEmbeddedProfileMetricsWithoutProfile) {
  738. ASSERT_FALSE(PathExists(metrics_file()));
  739. CreateMetricsFileWithHistograms(2);
  740. // Register the file and allow the "checker" task to run.
  741. ASSERT_TRUE(PathExists(metrics_file()));
  742. provider()->RegisterSource(FileMetricsProvider::Params(
  743. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_FILE,
  744. FileMetricsProvider::ASSOCIATE_INTERNAL_PROFILE, kMetricsName));
  745. // Record embedded snapshots via snapshot-manager.
  746. OnDidCreateMetricsLog();
  747. RunTasks();
  748. {
  749. HistogramFlattenerDeltaRecorder flattener;
  750. base::HistogramSnapshotManager snapshot_manager(&flattener);
  751. ChromeUserMetricsExtension uma_proto;
  752. // A read of metrics with internal profiles should return nothing.
  753. EXPECT_FALSE(HasIndependentMetrics());
  754. EXPECT_FALSE(ProvideIndependentMetrics(&uma_proto, &snapshot_manager));
  755. }
  756. EXPECT_TRUE(base::PathExists(metrics_file()));
  757. OnDidCreateMetricsLog();
  758. RunTasks();
  759. EXPECT_FALSE(base::PathExists(metrics_file()));
  760. }
  761. TEST_P(FileMetricsProviderTest, AccessEmbeddedProfileMetricsWithProfile) {
  762. ASSERT_FALSE(PathExists(metrics_file()));
  763. CreateMetricsFileWithHistograms(
  764. metrics_file(), base::Time::Now(), 2,
  765. base::BindOnce([](base::PersistentHistogramAllocator* allocator) {
  766. SystemProfileProto profile_proto;
  767. SystemProfileProto::FieldTrial* trial = profile_proto.add_field_trial();
  768. trial->set_name_id(123);
  769. trial->set_group_id(456);
  770. PersistentSystemProfile persistent_profile;
  771. persistent_profile.RegisterPersistentAllocator(
  772. allocator->memory_allocator());
  773. persistent_profile.SetSystemProfile(profile_proto, true);
  774. }));
  775. // Register the file and allow the "checker" task to run.
  776. ASSERT_TRUE(PathExists(metrics_file()));
  777. provider()->RegisterSource(FileMetricsProvider::Params(
  778. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_FILE,
  779. FileMetricsProvider::ASSOCIATE_INTERNAL_PROFILE, kMetricsName));
  780. // Record embedded snapshots via snapshot-manager.
  781. OnDidCreateMetricsLog();
  782. RunTasks();
  783. {
  784. HistogramFlattenerDeltaRecorder flattener;
  785. base::HistogramSnapshotManager snapshot_manager(&flattener);
  786. RecordInitialHistogramSnapshots(&snapshot_manager);
  787. EXPECT_EQ(0U, flattener.GetRecordedDeltaHistogramNames().size());
  788. // A read of metrics with internal profiles should return one result.
  789. ChromeUserMetricsExtension uma_proto;
  790. EXPECT_TRUE(HasIndependentMetrics());
  791. EXPECT_TRUE(ProvideIndependentMetrics(&uma_proto, &snapshot_manager));
  792. EXPECT_FALSE(HasIndependentMetrics());
  793. EXPECT_FALSE(ProvideIndependentMetrics(&uma_proto, &snapshot_manager));
  794. }
  795. RunTasks();
  796. EXPECT_FALSE(base::PathExists(metrics_file()));
  797. }
  798. TEST_P(FileMetricsProviderTest, AccessEmbeddedFallbackMetricsWithoutProfile) {
  799. ASSERT_FALSE(PathExists(metrics_file()));
  800. CreateMetricsFileWithHistograms(2);
  801. // Register the file and allow the "checker" task to run.
  802. ASSERT_TRUE(PathExists(metrics_file()));
  803. provider()->RegisterSource(FileMetricsProvider::Params(
  804. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_FILE,
  805. FileMetricsProvider::ASSOCIATE_INTERNAL_PROFILE_OR_PREVIOUS_RUN,
  806. kMetricsName));
  807. // Record embedded snapshots via snapshot-manager.
  808. ASSERT_TRUE(HasPreviousSessionData());
  809. RunTasks();
  810. {
  811. HistogramFlattenerDeltaRecorder flattener;
  812. base::HistogramSnapshotManager snapshot_manager(&flattener);
  813. RecordInitialHistogramSnapshots(&snapshot_manager);
  814. EXPECT_EQ(2U, flattener.GetRecordedDeltaHistogramNames().size());
  815. // A read of metrics with internal profiles should return nothing.
  816. ChromeUserMetricsExtension uma_proto;
  817. EXPECT_FALSE(HasIndependentMetrics());
  818. EXPECT_FALSE(ProvideIndependentMetrics(&uma_proto, &snapshot_manager));
  819. }
  820. EXPECT_TRUE(base::PathExists(metrics_file()));
  821. OnDidCreateMetricsLog();
  822. RunTasks();
  823. EXPECT_FALSE(base::PathExists(metrics_file()));
  824. }
  825. TEST_P(FileMetricsProviderTest, AccessEmbeddedFallbackMetricsWithProfile) {
  826. ASSERT_FALSE(PathExists(metrics_file()));
  827. CreateMetricsFileWithHistograms(
  828. metrics_file(), base::Time::Now(), 2,
  829. base::BindOnce([](base::PersistentHistogramAllocator* allocator) {
  830. SystemProfileProto profile_proto;
  831. SystemProfileProto::FieldTrial* trial = profile_proto.add_field_trial();
  832. trial->set_name_id(123);
  833. trial->set_group_id(456);
  834. PersistentSystemProfile persistent_profile;
  835. persistent_profile.RegisterPersistentAllocator(
  836. allocator->memory_allocator());
  837. persistent_profile.SetSystemProfile(profile_proto, true);
  838. }));
  839. // Register the file and allow the "checker" task to run.
  840. ASSERT_TRUE(PathExists(metrics_file()));
  841. provider()->RegisterSource(FileMetricsProvider::Params(
  842. metrics_file(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_FILE,
  843. FileMetricsProvider::ASSOCIATE_INTERNAL_PROFILE_OR_PREVIOUS_RUN,
  844. kMetricsName));
  845. // Record embedded snapshots via snapshot-manager.
  846. EXPECT_FALSE(HasPreviousSessionData());
  847. RunTasks();
  848. {
  849. HistogramFlattenerDeltaRecorder flattener;
  850. base::HistogramSnapshotManager snapshot_manager(&flattener);
  851. RecordInitialHistogramSnapshots(&snapshot_manager);
  852. EXPECT_EQ(0U, flattener.GetRecordedDeltaHistogramNames().size());
  853. // A read of metrics with internal profiles should return one result.
  854. ChromeUserMetricsExtension uma_proto;
  855. EXPECT_TRUE(HasIndependentMetrics());
  856. EXPECT_TRUE(ProvideIndependentMetrics(&uma_proto, &snapshot_manager));
  857. EXPECT_FALSE(HasIndependentMetrics());
  858. EXPECT_FALSE(ProvideIndependentMetrics(&uma_proto, &snapshot_manager));
  859. }
  860. RunTasks();
  861. EXPECT_FALSE(base::PathExists(metrics_file()));
  862. }
  863. TEST_P(FileMetricsProviderTest, AccessEmbeddedProfileMetricsFromDir) {
  864. const int file_count = 3;
  865. base::Time file_base_time = base::Time::Now();
  866. std::vector<base::FilePath> file_names;
  867. for (int i = 0; i < file_count; ++i) {
  868. CreateMetricsFileWithHistograms(
  869. metrics_file(), base::Time::Now(), 2,
  870. base::BindOnce([](base::PersistentHistogramAllocator* allocator) {
  871. SystemProfileProto profile_proto;
  872. SystemProfileProto::FieldTrial* trial =
  873. profile_proto.add_field_trial();
  874. trial->set_name_id(123);
  875. trial->set_group_id(456);
  876. PersistentSystemProfile persistent_profile;
  877. persistent_profile.RegisterPersistentAllocator(
  878. allocator->memory_allocator());
  879. persistent_profile.SetSystemProfile(profile_proto, true);
  880. }));
  881. ASSERT_TRUE(PathExists(metrics_file()));
  882. char new_name[] = "hX";
  883. new_name[1] = '1' + i;
  884. base::FilePath file_name = temp_dir().AppendASCII(new_name).AddExtension(
  885. base::PersistentMemoryAllocator::kFileExtension);
  886. base::Time file_time = file_base_time - base::Minutes(file_count - i);
  887. base::TouchFile(metrics_file(), file_time, file_time);
  888. base::Move(metrics_file(), file_name);
  889. file_names.push_back(std::move(file_name));
  890. }
  891. // Register the file and allow the "checker" task to run.
  892. provider()->RegisterSource(FileMetricsProvider::Params(
  893. temp_dir(), FileMetricsProvider::SOURCE_HISTOGRAMS_ATOMIC_DIR,
  894. FileMetricsProvider::ASSOCIATE_INTERNAL_PROFILE));
  895. OnDidCreateMetricsLog();
  896. RunTasks();
  897. // A read of metrics with internal profiles should return one result.
  898. HistogramFlattenerDeltaRecorder flattener;
  899. base::HistogramSnapshotManager snapshot_manager(&flattener);
  900. ChromeUserMetricsExtension uma_proto;
  901. for (int i = 0; i < file_count; ++i) {
  902. EXPECT_TRUE(HasIndependentMetrics()) << i;
  903. EXPECT_TRUE(ProvideIndependentMetrics(&uma_proto, &snapshot_manager)) << i;
  904. RunTasks();
  905. }
  906. EXPECT_FALSE(HasIndependentMetrics());
  907. EXPECT_FALSE(ProvideIndependentMetrics(&uma_proto, &snapshot_manager));
  908. OnDidCreateMetricsLog();
  909. RunTasks();
  910. for (const auto& file_name : file_names)
  911. EXPECT_FALSE(base::PathExists(file_name));
  912. }
  913. } // namespace metrics