File: subprocess_metrics_provider_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (388 lines) | stat: -rw-r--r-- 15,942 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/metrics/content/subprocess_metrics_provider.h"

#include <memory>
#include <string>
#include <vector>

#include "base/metrics/histogram.h"
#include "base/metrics/histogram_flattener.h"
#include "base/metrics/histogram_snapshot_manager.h"
#include "base/metrics/persistent_histogram_allocator.h"
#include "base/metrics/persistent_memory_allocator.h"
#include "base/metrics/sparse_histogram.h"
#include "base/metrics/statistics_recorder.h"
#include "base/test/bind.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::IsEmpty;
using ::testing::UnorderedElementsAre;

namespace metrics {
namespace {

const uint32_t TEST_MEMORY_SIZE = 64 << 10;  // 64 KiB

struct HistogramData {
  const std::string histogram_name;
  const base::HistogramBase::Count32 total_count;
  const int64_t sum;

  HistogramData(std::string_view name,
                base::HistogramBase::Count32 count,
                int64_t sum)
      : histogram_name(name), total_count(count), sum(sum) {}

  bool operator==(const HistogramData& other) const {
    return histogram_name == other.histogram_name &&
           total_count == other.total_count && sum == other.sum;
  }
};

class HistogramFlattenerDeltaRecorder : public base::HistogramFlattener {
 public:
  HistogramFlattenerDeltaRecorder() = default;

  HistogramFlattenerDeltaRecorder(const HistogramFlattenerDeltaRecorder&) =
      delete;
  HistogramFlattenerDeltaRecorder& operator=(
      const HistogramFlattenerDeltaRecorder&) = delete;

  ~HistogramFlattenerDeltaRecorder() override = default;

  void RecordDelta(const base::HistogramBase& histogram,
                   const base::HistogramSamples& snapshot) override {
    // Only record histograms that start with '_' (e.g., _foo, _bar, _baz) to
    // not record histograms from outside what is being tested.
    if (histogram.histogram_name()[0] == '_') {
      recorded_delta_histograms_.emplace_back(
          histogram.histogram_name(), snapshot.TotalCount(), snapshot.sum());
    }
  }

  const std::vector<HistogramData>& GetRecordedDeltaHistograms() {
    return recorded_delta_histograms_;
  }

 private:
  std::vector<HistogramData> recorded_delta_histograms_;
};

// Same as PersistentHistogramAllocator, but will call a callback on being
// destroyed.
class TestPersistentHistogramAllocator
    : public base::PersistentHistogramAllocator {
 public:
  using base::PersistentHistogramAllocator::PersistentHistogramAllocator;

  TestPersistentHistogramAllocator(const TestPersistentHistogramAllocator&) =
      delete;
  TestPersistentHistogramAllocator& operator=(
      const TestPersistentHistogramAllocator&) = delete;

  ~TestPersistentHistogramAllocator() override {
    if (!destroyed_callback_.is_null()) {
      std::move(destroyed_callback_).Run();
    }
  }

  void SetDestroyedCallback(base::OnceClosure destroyed_callback) {
    destroyed_callback_ = std::move(destroyed_callback);
  }

 private:
  base::OnceClosure destroyed_callback_;
};

}  // namespace

class SubprocessMetricsProviderTest : public testing::Test {
 public:
  SubprocessMetricsProviderTest(const SubprocessMetricsProviderTest&) = delete;
  SubprocessMetricsProviderTest& operator=(
      const SubprocessMetricsProviderTest&) = delete;

 protected:
  SubprocessMetricsProviderTest()
      : task_environment_(
            // Use ThreadPoolExecutionMode::QUEUED so that tests can decide
            // exactly when tasks posted to ThreadPool start running.
            base::test::TaskEnvironment::ThreadPoolExecutionMode::QUEUED) {
    SubprocessMetricsProvider::CreateInstance();

    // Need to recreate a task runner, otherwise it may be a stale one from a
    // previous test (it's possible the global instance is reused across
    // tests).
    RecreateTaskRunnerForTesting();

    // MergeHistogramDeltas needs to be called because it uses a histogram
    // macro which caches a pointer to a histogram. If not done before setting
    // a persistent global allocator, then it would point into memory that
    // will go away.
    SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

    // Create a dedicated StatisticsRecorder for this test.
    test_recorder_ = base::StatisticsRecorder::CreateTemporaryForTesting();

    // Create a global allocator using a block of memory from the heap.
    base::GlobalHistogramAllocator::CreateWithLocalMemory(TEST_MEMORY_SIZE, 0,
                                                          "");
  }

  ~SubprocessMetricsProviderTest() override {
    base::GlobalHistogramAllocator::ReleaseForTesting();
  }

  std::unique_ptr<TestPersistentHistogramAllocator> CreateDuplicateAllocator(
      base::PersistentHistogramAllocator* allocator) {
    // Just wrap around the data segment in-use by the passed allocator.
    return std::make_unique<TestPersistentHistogramAllocator>(
        std::make_unique<base::PersistentMemoryAllocator>(
            const_cast<void*>(allocator->data()), allocator->length(), 0, 0, "",
            base::PersistentMemoryAllocator::kReadWrite));
  }

  std::vector<HistogramData> GetSnapshotHistograms() {
    // Flatten what is known to see what has changed since the last time.
    HistogramFlattenerDeltaRecorder flattener;
    base::HistogramSnapshotManager snapshot_manager(&flattener);
    // "true" to the begin() includes histograms held in persistent storage.
    base::StatisticsRecorder::PrepareDeltas(true, base::Histogram::kNoFlags,
                                            base::Histogram::kNoFlags,
                                            &snapshot_manager);
    return flattener.GetRecordedDeltaHistograms();
  }

  void RegisterSubprocessAllocator(
      int id,
      std::unique_ptr<base::PersistentHistogramAllocator> allocator) {
    SubprocessMetricsProvider::GetInstance()->RegisterSubprocessAllocator(
        id, std::move(allocator));
  }

  void DeregisterSubprocessAllocator(int id) {
    SubprocessMetricsProvider::GetInstance()->DeregisterSubprocessAllocator(id);
  }

  void RecreateTaskRunnerForTesting() {
    SubprocessMetricsProvider::GetInstance()->RecreateTaskRunnerForTesting();
  }

  content::BrowserTaskEnvironment* task_environment() {
    return &task_environment_;
  }

 private:
  // A thread-bundle makes the tests appear on the UI thread, something that is
  // checked in methods called from the SubprocessMetricsProvider class under
  // test. This must be constructed before the |provider_| field.
  content::BrowserTaskEnvironment task_environment_;

  std::unique_ptr<base::StatisticsRecorder> test_recorder_;
};

TEST_F(SubprocessMetricsProviderTest, SnapshotMetrics) {
  base::HistogramBase* foo = base::Histogram::FactoryGet("_foo", 1, 100, 10, 0);
  base::HistogramBase* bar = base::Histogram::FactoryGet("_bar", 1, 100, 10, 0);
  base::HistogramBase* baz = base::Histogram::FactoryGet("_baz", 1, 100, 10, 0);
  base::HistogramBase* foobar = base::SparseHistogram::FactoryGet(
      "_foobar", base::HistogramBase::kUmaTargetedHistogramFlag);
  foo->Add(42);
  bar->Add(84);
  foobar->Add(1);
  foobar->Add(2);
  foobar->Add(3);

  // Register a new allocator that duplicates the global one.
  base::GlobalHistogramAllocator* global_allocator(
      base::GlobalHistogramAllocator::ReleaseForTesting());
  auto duplicate_allocator = CreateDuplicateAllocator(global_allocator);
  bool duplicate_allocator_destroyed = false;
  duplicate_allocator->SetDestroyedCallback(base::BindLambdaForTesting(
      [&] { duplicate_allocator_destroyed = true; }));
  RegisterSubprocessAllocator(123, std::move(duplicate_allocator));

  // Recording should find the two histograms created in persistent memory.
  SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
  EXPECT_THAT(GetSnapshotHistograms(),
              UnorderedElementsAre(
                  HistogramData{"_foo", /*total_count=*/1, /*sum=*/42},
                  HistogramData{"_bar", /*total_count=*/1, /*sum=*/84},
                  HistogramData{"_foobar", /*total_count=*/3, /*sum=*/6}));

  // A second run should have nothing to produce.
  SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());

  // Create a new histogram and update existing ones. Should now report 3 items.
  baz->Add(1969);
  foo->Add(10);
  bar->Add(20);
  foobar->Add(4);
  SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
  EXPECT_THAT(GetSnapshotHistograms(),
              UnorderedElementsAre(
                  HistogramData{"_foo", /*total_count=*/1, /*sum=*/10},
                  HistogramData{"_bar", /*total_count=*/1, /*sum=*/20},
                  HistogramData{"_baz", /*total_count=*/1, /*sum=*/1969},
                  HistogramData{"_foobar", /*total_count=*/1, /*sum=*/4}));

  // Ensure that deregistering does a final merge of the data.
  foo->Add(10);
  bar->Add(20);
  DeregisterSubprocessAllocator(123);
  // Do not call MergeHistogramDeltas() here, because the call to
  // DeregisterSubprocessAllocator() should have already scheduled a task to
  // merge the histograms.
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());
  task_environment()->RunUntilIdle();
  EXPECT_THAT(GetSnapshotHistograms(),
              UnorderedElementsAre(
                  HistogramData{"_foo", /*total_count=*/1, /*sum=*/10},
                  HistogramData{"_bar", /*total_count=*/1, /*sum=*/20}));
  // The allocator should have been released after deregistering.
  EXPECT_TRUE(duplicate_allocator_destroyed);

  // Further snapshots should be empty even if things have changed.
  foo->Add(10);
  bar->Add(20);
  SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());
}

TEST_F(SubprocessMetricsProviderTest, SnapshotMetricsAsync) {
  base::HistogramBase* foo = base::Histogram::FactoryGet("_foo", 1, 100, 10, 0);
  base::HistogramBase* bar = base::Histogram::FactoryGet("_bar", 1, 100, 10, 0);
  base::HistogramBase* baz = base::Histogram::FactoryGet("_baz", 1, 100, 10, 0);
  base::HistogramBase* foobar = base::SparseHistogram::FactoryGet(
      "_foobar", base::HistogramBase::kUmaTargetedHistogramFlag);
  foo->Add(42);
  bar->Add(84);
  foobar->Add(1);
  foobar->Add(2);
  foobar->Add(3);

  // Register a new allocator that duplicates the global one.
  base::GlobalHistogramAllocator* global_allocator(
      base::GlobalHistogramAllocator::ReleaseForTesting());
  RegisterSubprocessAllocator(123, CreateDuplicateAllocator(global_allocator));

  // Recording should find the two histograms created in persistent memory.
  SubprocessMetricsProvider::MergeHistogramDeltasForTesting(
      /*async=*/true, /*done_callback=*/task_environment()->QuitClosure());
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());
  task_environment()->RunUntilQuit();
  EXPECT_THAT(GetSnapshotHistograms(),
              UnorderedElementsAre(
                  HistogramData{"_foo", /*total_count=*/1, /*sum=*/42},
                  HistogramData{"_bar", /*total_count=*/1, /*sum=*/84},
                  HistogramData{"_foobar", /*total_count=*/3, /*sum=*/6}));

  // A second run should have nothing to produce.
  SubprocessMetricsProvider::MergeHistogramDeltasForTesting(
      /*async=*/true, /*done_callback=*/task_environment()->QuitClosure());
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());
  task_environment()->RunUntilQuit();
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());

  // Create a new histogram and update existing ones. Should now report 3 items.
  baz->Add(1969);
  foo->Add(10);
  bar->Add(20);
  foobar->Add(4);
  SubprocessMetricsProvider::MergeHistogramDeltasForTesting(
      /*async=*/true, /*done_callback=*/task_environment()->QuitClosure());
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());
  task_environment()->RunUntilQuit();
  EXPECT_THAT(GetSnapshotHistograms(),
              UnorderedElementsAre(
                  HistogramData{"_foo", /*total_count=*/1, /*sum=*/10},
                  HistogramData{"_bar", /*total_count=*/1, /*sum=*/20},
                  HistogramData{"_baz", /*total_count=*/1, /*sum=*/1969},
                  HistogramData{"_foobar", /*total_count=*/1, /*sum=*/4}));

  // Ensure that deregistering does a final merge of the data.
  foo->Add(10);
  bar->Add(20);
  DeregisterSubprocessAllocator(123);
  // Do not call MergeHistogramDeltas() here, because the call to
  // DeregisterSubprocessAllocator() should have already scheduled a task to
  // merge the histograms.
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());
  task_environment()->RunUntilIdle();
  EXPECT_THAT(GetSnapshotHistograms(),
              UnorderedElementsAre(
                  HistogramData{"_foo", /*total_count=*/1, /*sum=*/10},
                  HistogramData{"_bar", /*total_count=*/1, /*sum=*/20}));

  // Further snapshots should be empty even if things have changed.
  foo->Add(10);
  bar->Add(20);
  SubprocessMetricsProvider::MergeHistogramDeltasForTesting(
      /*async=*/true, /*done_callback=*/task_environment()->QuitClosure());
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());
  task_environment()->RunUntilQuit();
  EXPECT_THAT(GetSnapshotHistograms(), IsEmpty());
}

// Verifies that it is fine to deregister an allocator even if background tasks
// that access it are still pending/running.
TEST_F(SubprocessMetricsProviderTest, AllocatorRefCounted) {
  base::HistogramBase* foo = base::Histogram::FactoryGet("_foo", 1, 100, 10, 0);
  base::HistogramBase* bar = base::Histogram::FactoryGet("_bar", 1, 100, 10, 0);
  base::HistogramBase* baz = base::SparseHistogram::FactoryGet(
      "_baz", base::HistogramBase::kUmaTargetedHistogramFlag);
  base::HistogramBase* foobar = base::SparseHistogram::FactoryGet(
      "_foobar", base::HistogramBase::kUmaTargetedHistogramFlag);
  foo->Add(42);
  bar->Add(84);
  baz->Add(1);
  baz->Add(2);
  baz->Add(3);
  foobar->Add(4);
  foobar->Add(5);
  foobar->Add(6);

  // Register a new allocator that duplicates the global one.
  base::GlobalHistogramAllocator* global_allocator(
      base::GlobalHistogramAllocator::ReleaseForTesting());
  auto duplicate_allocator = CreateDuplicateAllocator(global_allocator);
  bool duplicate_allocator_destroyed = false;
  duplicate_allocator->SetDestroyedCallback(base::BindLambdaForTesting(
      [&] { duplicate_allocator_destroyed = true; }));
  RegisterSubprocessAllocator(123, std::move(duplicate_allocator));

  // Merge histogram deltas. This will be done asynchronously.
  SubprocessMetricsProvider::MergeHistogramDeltasForTesting(
      /*async=*/true, /*done_callback=*/base::DoNothing());
  // Deregister the allocator. This will be done asynchronously.
  DeregisterSubprocessAllocator(123);

  // The call to DeregisterSubprocessAllocator() above will have removed the
  // allocator from the internal map. However, the allocator should not have
  // been freed yet as there are still background tasks pending/running
  // that have a reference to it (i.e., the tasks from MergeHistogramDeltas()
  // and DeregisterSubprocessAllocator()).
  ASSERT_FALSE(duplicate_allocator_destroyed);

  // Run tasks.
  task_environment()->RunUntilIdle();

  // After all the tasks have finished, the allocator should have been released.
  EXPECT_TRUE(duplicate_allocator_destroyed);

  // Verify that the histograms were merged.
  EXPECT_THAT(GetSnapshotHistograms(),
              UnorderedElementsAre(
                  HistogramData{"_foo", /*total_count=*/1, /*sum=*/42},
                  HistogramData{"_bar", /*total_count=*/1, /*sum=*/84},
                  HistogramData{"_baz", /*total_count=*/3, /*sum=*/6},
                  HistogramData{"_foobar", /*total_count=*/3, /*sum=*/15}));
}

}  // namespace metrics