File: stack_sampling_recorder_unittest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (342 lines) | stat: -rw-r--r-- 13,993 bytes parent folder | download | duplicates (4)
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
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "components/metrics/call_stacks/stack_sampling_recorder.h"

#include <sys/file.h>

#include <memory>
#include <utility>

#include "base/check.h"
#include "base/containers/span.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_refptr.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "components/metrics/call_stacks/call_stack_profile_metrics_provider.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/proto/stack_sampled_metrics_status/stack_sampled_metrics_status.pb.h"
#include "third_party/metrics_proto/execution_context.pb.h"

namespace metrics {

using ::stack_sampled_metrics_status::StackSampledMetricsStatus;

// A version of StackSamplingRecorder that overrides
// GetSuccessfullyCollectedCounts() to return a test-provided list of
// process/thread/counts.
class TestingStackSamplingRecorder : public StackSamplingRecorder {
 public:
  explicit TestingStackSamplingRecorder(base::FilePath file_path)
      : StackSamplingRecorder(std::move(file_path)) {}

  void SetSuccessfullyCollectedCounts(
      const metrics::CallStackProfileMetricsProvider::ProcessThreadCount&
          counts) {
    counts_ = counts;
  }

  // Allow tests to access the private function WriteFileHelper().
  void WriteFileHelper() { StackSamplingRecorder::WriteFileHelper(); }

 private:
  ~TestingStackSamplingRecorder() override = default;

  metrics::CallStackProfileMetricsProvider::ProcessThreadCount
  GetSuccessfullyCollectedCounts() const override {
    return counts_;
  }

  metrics::CallStackProfileMetricsProvider::ProcessThreadCount counts_;
};

class StackSamplingRecorderTest : public testing::Test {
 protected:
  void SetUp() override {
    CHECK(tmp_dir_.CreateUniqueTempDir());

    output_path_ = tmp_dir_.GetPath().Append("stack-sampling-data");
    recorder_ =
        base::MakeRefCounted<TestingStackSamplingRecorder>(output_path_);
  }

  base::ScopedTempDir tmp_dir_;
  base::FilePath output_path_;
  scoped_refptr<TestingStackSamplingRecorder> recorder_;
};

TEST_F(StackSamplingRecorderTest, ProducesValidFile) {
  metrics::CallStackProfileMetricsProvider::ProcessThreadCount counts;
  counts[metrics::BROWSER_PROCESS][metrics::MAIN_THREAD] = 5;
  counts[metrics::BROWSER_PROCESS][metrics::FILE_THREAD] = 7;
  counts[metrics::BROWSER_PROCESS][metrics::IO_THREAD] = 9;
  counts[metrics::RENDERER_PROCESS][metrics::MAIN_THREAD] = 11;
  counts[metrics::UTILITY_PROCESS][metrics::IO_THREAD] = 13;
  recorder_->SetSuccessfullyCollectedCounts(counts);

  recorder_->WriteFileHelper();

  base::File result_file(output_path_,
                         base::File::FLAG_OPEN | base::File::FLAG_READ);
  ASSERT_TRUE(result_file.IsValid());

  StackSampledMetricsStatus result;
  EXPECT_TRUE(result.ParseFromFileDescriptor(result_file.GetPlatformFile()));

  // base::test::EqualsProto() doesn't work well on MessageLite's. Validate
  // `result` manually.
  EXPECT_EQ(result.process_type_to_thread_count_map().size(), 3UL);

  ASSERT_TRUE(result.process_type_to_thread_count_map().contains(
      metrics::BROWSER_PROCESS));
  const StackSampledMetricsStatus::ThreadCountMap& browser_thread_count =
      result.process_type_to_thread_count_map().at(metrics::BROWSER_PROCESS);
  EXPECT_EQ(browser_thread_count.thread_type_to_success_count().size(), 3UL);
  ASSERT_TRUE(browser_thread_count.thread_type_to_success_count().contains(
      metrics::MAIN_THREAD));
  EXPECT_EQ(browser_thread_count.thread_type_to_success_count().at(
                metrics::MAIN_THREAD),
            5);
  ASSERT_TRUE(browser_thread_count.thread_type_to_success_count().contains(
      metrics::FILE_THREAD));
  EXPECT_EQ(browser_thread_count.thread_type_to_success_count().at(
                metrics::FILE_THREAD),
            7);
  ASSERT_TRUE(browser_thread_count.thread_type_to_success_count().contains(
      metrics::IO_THREAD));
  EXPECT_EQ(browser_thread_count.thread_type_to_success_count().at(
                metrics::IO_THREAD),
            9);

  ASSERT_TRUE(result.process_type_to_thread_count_map().contains(
      metrics::RENDERER_PROCESS));
  const StackSampledMetricsStatus::ThreadCountMap& renderer_thread_count =
      result.process_type_to_thread_count_map().at(metrics::RENDERER_PROCESS);
  EXPECT_EQ(renderer_thread_count.thread_type_to_success_count().size(), 1UL);
  ASSERT_TRUE(renderer_thread_count.thread_type_to_success_count().contains(
      metrics::MAIN_THREAD));
  EXPECT_EQ(renderer_thread_count.thread_type_to_success_count().at(
                metrics::MAIN_THREAD),
            11);

  ASSERT_TRUE(result.process_type_to_thread_count_map().contains(
      metrics::UTILITY_PROCESS));
  const StackSampledMetricsStatus::ThreadCountMap& utility_thread_count =
      result.process_type_to_thread_count_map().at(metrics::UTILITY_PROCESS);
  EXPECT_EQ(utility_thread_count.thread_type_to_success_count().size(), 1UL);
  ASSERT_TRUE(utility_thread_count.thread_type_to_success_count().contains(
      metrics::IO_THREAD));
  EXPECT_EQ(utility_thread_count.thread_type_to_success_count().at(
                metrics::IO_THREAD),
            13);
}

TEST_F(StackSamplingRecorderTest, ProducesValidEmptyFileIfNoCounts) {
  recorder_->WriteFileHelper();

  base::File result_file(output_path_,
                         base::File::FLAG_OPEN | base::File::FLAG_READ);
  ASSERT_TRUE(result_file.IsValid());

  StackSampledMetricsStatus result;
  EXPECT_TRUE(result.ParseFromFileDescriptor(result_file.GetPlatformFile()));
  EXPECT_EQ(result.process_type_to_thread_count_map().size(), 0UL);
}

TEST_F(StackSamplingRecorderTest, TruncatesExistingFileToEmpty) {
  // Add some existing data.
  metrics::CallStackProfileMetricsProvider::ProcessThreadCount counts;
  counts[metrics::BROWSER_PROCESS][metrics::MAIN_THREAD] = 5;
  counts[metrics::BROWSER_PROCESS][metrics::FILE_THREAD] = 7;
  counts[metrics::BROWSER_PROCESS][metrics::IO_THREAD] = 9;
  counts[metrics::RENDERER_PROCESS][metrics::MAIN_THREAD] = 11;
  counts[metrics::UTILITY_PROCESS][metrics::IO_THREAD] = 13;
  recorder_->SetSuccessfullyCollectedCounts(counts);

  recorder_->WriteFileHelper();

  // Rewrite with no count.
  recorder_->SetSuccessfullyCollectedCounts({});
  recorder_->WriteFileHelper();

  std::optional<int64_t> file_size = base::GetFileSize(output_path_);
  ASSERT_TRUE(file_size.has_value());
  EXPECT_EQ(file_size.value(), 0L);
}

TEST_F(StackSamplingRecorderTest, TruncatesExistingFileWithLessData) {
  // Add some existing data.
  metrics::CallStackProfileMetricsProvider::ProcessThreadCount counts;
  counts[metrics::BROWSER_PROCESS][metrics::MAIN_THREAD] = 5;
  counts[metrics::BROWSER_PROCESS][metrics::FILE_THREAD] = 7;
  counts[metrics::BROWSER_PROCESS][metrics::IO_THREAD] = 9;
  counts[metrics::RENDERER_PROCESS][metrics::MAIN_THREAD] = 11;
  counts[metrics::UTILITY_PROCESS][metrics::IO_THREAD] = 13;
  recorder_->SetSuccessfullyCollectedCounts(counts);

  recorder_->WriteFileHelper();

  // Rewrite with a different, smaller set of counts.
  counts.clear();
  counts[metrics::GPU_PROCESS][metrics::FILE_THREAD] = 15;
  counts[metrics::UTILITY_PROCESS][metrics::MAIN_THREAD] = 17;

  recorder_->SetSuccessfullyCollectedCounts(counts);
  recorder_->WriteFileHelper();

  base::File result_file(output_path_,
                         base::File::FLAG_OPEN | base::File::FLAG_READ);
  ASSERT_TRUE(result_file.IsValid());

  // Confirm that result only contains the new counts, not the old counts.
  StackSampledMetricsStatus result;
  EXPECT_TRUE(result.ParseFromFileDescriptor(result_file.GetPlatformFile()));

  // base::test::EqualsProto() doesn't work well on MessageLite's. Validate
  // `result` manually.
  EXPECT_EQ(result.process_type_to_thread_count_map().size(), 2UL);

  ASSERT_TRUE(
      result.process_type_to_thread_count_map().contains(metrics::GPU_PROCESS));
  const StackSampledMetricsStatus::ThreadCountMap& gpu_thread_count =
      result.process_type_to_thread_count_map().at(metrics::GPU_PROCESS);
  EXPECT_EQ(gpu_thread_count.thread_type_to_success_count().size(), 1UL);
  ASSERT_TRUE(gpu_thread_count.thread_type_to_success_count().contains(
      metrics::FILE_THREAD));
  EXPECT_EQ(
      gpu_thread_count.thread_type_to_success_count().at(metrics::FILE_THREAD),
      15);

  ASSERT_TRUE(result.process_type_to_thread_count_map().contains(
      metrics::UTILITY_PROCESS));
  const StackSampledMetricsStatus::ThreadCountMap& utility_thread_count =
      result.process_type_to_thread_count_map().at(metrics::UTILITY_PROCESS);
  EXPECT_EQ(utility_thread_count.thread_type_to_success_count().size(), 1UL);
  ASSERT_TRUE(utility_thread_count.thread_type_to_success_count().contains(
      metrics::MAIN_THREAD));
  EXPECT_EQ(utility_thread_count.thread_type_to_success_count().at(
                metrics::MAIN_THREAD),
            17);
}

TEST_F(StackSamplingRecorderTest, DoesNotCrashOnUnwritableFile) {
  // Will prevent normal file opens from working:
  ASSERT_TRUE(base::CreateDirectory(output_path_));

  metrics::CallStackProfileMetricsProvider::ProcessThreadCount counts;
  counts[metrics::GPU_PROCESS][metrics::FILE_THREAD] = 15;
  counts[metrics::UTILITY_PROCESS][metrics::MAIN_THREAD] = 17;
  recorder_->SetSuccessfullyCollectedCounts(counts);

  recorder_->WriteFileHelper();
}

// Called on a second thread to make sure the file doesn't change while locked.
// Specifically:
// 1. Writes a known pattern into the file
// 2. Locks the file
// 3. Signals that it has locked the file
// 4. Waits for the other thread to try & write to the file
// 5. CHECKs that the file still contains the original pattern
static void LockFileAndPreventChange(base::FilePath path,
                                     base::WaitableEvent* waitable) {
  // 1. Write a known pattern into the file
  base::File file(path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_READ |
                            base::File::FLAG_WRITE);
  CHECK(file.IsValid());
  constexpr char kPattern[] = "Not a valid proto";
  CHECK_EQ(file.Write(0, kPattern, sizeof(kPattern)),
           static_cast<int>(sizeof(kPattern)));

  // 2. Lock the file
  CHECK_EQ(HANDLE_EINTR(flock(file.GetPlatformFile(), LOCK_EX)), 0);

  // 3. Signal that it has locked the file
  waitable->Signal();

  // 4. Wait for the other thread to try & write to the file.
  //
  // Note: Yes, using Sleep here. There's no way for the other thread to signal
  // to this thread "I've started trying to lock the file and I am now blocked
  // waiting for the file to be unlocked." This can lead to anti-flakes (cases
  // where the test passes even thought the code-under-test is wrong -- if the
  // other thread doesn't start the write until the sleep is done) but shouldn't
  // lead to flakes.
  base::PlatformThreadBase::Sleep(base::Seconds(5));

  // 5. CHECK that the file still contains the original pattern.
  char buffer[sizeof(kPattern) + 1];
  CHECK_EQ(file.Read(0, buffer, sizeof(buffer)),
           static_cast<int>(sizeof(kPattern)));
  CHECK_EQ(std::string(buffer), std::string(kPattern));
}

TEST_F(StackSamplingRecorderTest, DoesNotWriteToLockedFile) {
  metrics::CallStackProfileMetricsProvider::ProcessThreadCount counts;
  counts[metrics::GPU_PROCESS][metrics::FILE_THREAD] = 15;
  counts[metrics::UTILITY_PROCESS][metrics::MAIN_THREAD] = 17;
  recorder_->SetSuccessfullyCollectedCounts(counts);

  base::WaitableEvent waitable;
  base::Thread thread("locker_thread");
  ASSERT_TRUE(thread.StartAndWaitForTesting());

  ASSERT_TRUE(thread.task_runner()->PostTask(
      FROM_HERE,
      base::BindOnce(&LockFileAndPreventChange, output_path_, &waitable)));

  // Wait for the locker to have locked the file.
  waitable.Wait();

  // Try to write. This should only return once the locker thread has released
  // the file lock.
  recorder_->WriteFileHelper();

  // The write should still have been successful once the lock is released.
  base::File result_file(output_path_,
                         base::File::FLAG_OPEN | base::File::FLAG_READ);
  ASSERT_TRUE(result_file.IsValid());

  // Confirm that result only contains the new counts, not the old counts.
  StackSampledMetricsStatus result;
  EXPECT_TRUE(result.ParseFromFileDescriptor(result_file.GetPlatformFile()));

  // base::test::EqualsProto() doesn't work well on MessageLite's. Validate
  // `result` manually.
  EXPECT_EQ(result.process_type_to_thread_count_map().size(), 2UL);

  ASSERT_TRUE(
      result.process_type_to_thread_count_map().contains(metrics::GPU_PROCESS));
  const StackSampledMetricsStatus::ThreadCountMap& gpu_thread_count =
      result.process_type_to_thread_count_map().at(metrics::GPU_PROCESS);
  EXPECT_EQ(gpu_thread_count.thread_type_to_success_count().size(), 1UL);
  ASSERT_TRUE(gpu_thread_count.thread_type_to_success_count().contains(
      metrics::FILE_THREAD));
  EXPECT_EQ(
      gpu_thread_count.thread_type_to_success_count().at(metrics::FILE_THREAD),
      15);

  ASSERT_TRUE(result.process_type_to_thread_count_map().contains(
      metrics::UTILITY_PROCESS));
  const StackSampledMetricsStatus::ThreadCountMap& utility_thread_count =
      result.process_type_to_thread_count_map().at(metrics::UTILITY_PROCESS);
  EXPECT_EQ(utility_thread_count.thread_type_to_success_count().size(), 1UL);
  ASSERT_TRUE(utility_thread_count.thread_type_to_success_count().contains(
      metrics::MAIN_THREAD));
  EXPECT_EQ(utility_thread_count.thread_type_to_success_count().at(
                metrics::MAIN_THREAD),
            17);
}

}  // namespace metrics