Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(146)

Side by Side Diff: chrome/browser/chromeos/resource_reporter/resource_reporter.cc

Issue 1374283003: Reporting top cpu and memory consumers via rappor on chromeos (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: more comments Created 5 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2015 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
5 #include "chrome/browser/chromeos/resource_reporter/resource_reporter.h"
6
7 #include <cstdint>
8 #include <queue>
9
10 #include "base/bind.h"
11 #include "base/rand_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/sys_info.h"
14 #include "chrome/browser/browser_process.h"
15 #include "chrome/browser/task_management/task_manager_interface.h"
16 #include "components/rappor/rappor_service.h"
17 #include "content/public/browser/browser_thread.h"
18
19 namespace chromeos {
20
21 namespace {
22
23 #define GET_ENUM_VAL(enum_entry) static_cast<int>(enum_entry)
24
25 // The task manager refresh interval, currently at 1 minute.
26 const int64_t kRefreshIntervalSeconds = 60;
27
28 // Various memory usage sizes in bytes.
29 const int64_t kMemory1GB = 1024 * 1024 * 1024;
30 const int64_t kMemory800MB = 800 * 1024 * 1024;
31 const int64_t kMemory600MB = 600 * 1024 * 1024;
32 const int64_t kMemory400MB = 400 * 1024 * 1024;
33 const int64_t kMemory200MB = 200 * 1024 * 1024;
34
35 // The name of the Rappor metric to report the CPU usage.
36 const char kCpuRapporMetric[] = "ResourceReporter.Cpu";
37
38 // The name of the Rappor metric to report the memory usage.
39 const char kMemoryRapporMetric[] = "ResourceReporter.Memory";
40
41 // The name of the string field of the Rappor metrics in which we'll record the
42 // task's Rappor sample name.
43 const char kRapporTaskStringField[] = "task";
44
45 // The name of the flags field of the Rappor metrics in which we'll store the
46 // priority of the process on which the task is running.
47 const char kRapporPriorityFlagsField[] = "priority";
48
49 // The name of the flags field of the CPU usage Rappor metrics in which we'll
50 // record the number of cores in the current system.
51 const char kRapporNumCoresRangeFlagsField[] = "num_cores_range";
52
53 // The name of the flags field of the Rappor metrics in which we'll store the
54 // CPU / memory usage ranges.
55 const char kRapporUsageRangeFlagsField[] = "usage_range";
56
57 // Currently set to be one day.
58 const int kMinimumTimeBetweenReportsInMs = 1 * 24 * 60 * 60 * 1000;
59
60 // A functor to sort the TaskRecords by their |cpu|.
61 struct TaskRecordCpuLessThan {
62 bool operator()(ResourceReporter::TaskRecord* const& lhs,
63 ResourceReporter::TaskRecord* const& rhs) const {
64 if (lhs->cpu_percent == rhs->cpu_percent)
65 return lhs->id < rhs->id;
66 return lhs->cpu_percent < rhs->cpu_percent;
67 }
68 };
69
70 // A functor to sort the TaskRecords by their |memory|.
71 struct TaskRecordMemoryLessThan {
72 bool operator()(ResourceReporter::TaskRecord* const& lhs,
73 ResourceReporter::TaskRecord* const& rhs) const {
74 if (lhs->memory_bytes == rhs->memory_bytes)
75 return lhs->id < rhs->id;
76 return lhs->memory_bytes < rhs->memory_bytes;
77 }
78 };
79
80 } // namespace
81
82 ResourceReporter::TaskRecord::TaskRecord(task_management::TaskId task_id)
83 : id(task_id), cpu_percent(0.0), memory_bytes(0), is_background(false) {
84 }
85
86 ResourceReporter::TaskRecord::TaskRecord(task_management::TaskId the_id,
87 const std::string& task_name,
88 double cpu_percent,
89 int64_t memory_bytes,
90 bool background)
91 : id(the_id),
92 task_name_for_rappor(task_name),
93 cpu_percent(cpu_percent),
94 memory_bytes(memory_bytes),
95 is_background(background) {
96 }
97
98 ResourceReporter::~ResourceReporter() {
99 }
100
101 // static
102 ResourceReporter* ResourceReporter::GetInstance() {
103 return base::Singleton<ResourceReporter>::get();
104 }
105
106 void ResourceReporter::StartMonitoring() {
107 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
108
109 if (is_monitoring_)
110 return;
111
112 is_monitoring_ = true;
113 task_management::TaskManagerInterface::GetTaskManager()->AddObserver(this);
114 memory_pressure_listener_.reset(new base::MemoryPressureListener(
115 base::Bind(&ResourceReporter::OnMemoryPressure, base::Unretained(this))));
116 }
117
118 void ResourceReporter::StopMonitoring() {
119 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
120
121 if (!is_monitoring_)
122 return;
123
124 is_monitoring_ = false;
125 memory_pressure_listener_.reset();
126 task_management::TaskManagerInterface::GetTaskManager()->RemoveObserver(this);
127 }
128
129 void ResourceReporter::OnTaskAdded(task_management::TaskId id) {
130 // Ignore this event.
131 }
132
133 void ResourceReporter::OnTaskToBeRemoved(task_management::TaskId id) {
134 auto it = task_records_.find(id);
135 if (it == task_records_.end())
136 return;
137
138 // Must be erased from the sorted set first.
139 // Note: this could mean that the sorted records are now less than
140 // |kTopConsumerCount| with other records in |task_records_| that can be
141 // added now. That's ok, we ignore this case.
142 auto cpu_it = std::find(task_records_by_cpu_.begin(),
143 task_records_by_cpu_.end(),
144 it->second.get());
145 if (cpu_it != task_records_by_cpu_.end())
146 task_records_by_cpu_.erase(cpu_it);
147
148 auto memory_it = std::find(task_records_by_memory_.begin(),
149 task_records_by_memory_.end(),
150 it->second.get());
151 if (memory_it != task_records_by_memory_.end())
152 task_records_by_memory_.erase(memory_it);
153
154 task_records_.erase(it);
155 }
156
157 void ResourceReporter::OnTasksRefreshed(
158 const task_management::TaskIdList& task_ids) {
159 // A priority queue to sort the task records by their |cpu|. Greatest |cpu|
160 // first.
161 std::priority_queue<TaskRecord*,
162 std::vector<TaskRecord*>,
163 TaskRecordCpuLessThan> records_by_cpu_queue;
164 // A priority queue to sort the task records by their |memory|. Greatest
165 // |memory| first.
166 std::priority_queue<TaskRecord*,
167 std::vector<TaskRecord*>,
168 TaskRecordMemoryLessThan> records_by_memory_queue;
169 task_records_by_cpu_.clear();
170 task_records_by_cpu_.reserve(kTopConsumersCount);
171 task_records_by_memory_.clear();
172 task_records_by_memory_.reserve(kTopConsumersCount);
173
174 for (const auto& id : task_ids) {
175 const double cpu_usage = observed_task_manager()->GetCpuUsage(id);
176 const int64_t memory_usage =
177 observed_task_manager()->GetPhysicalMemoryUsage(id);
178
179 // Browser and GPU processes are reported later using UMA histograms as they
180 // don't have any privacy issues.
181 const auto task_type = observed_task_manager()->GetType(id);
182 switch (task_type) {
183 case task_management::Task::UNKNOWN:
184 case task_management::Task::ZYGOTE:
185 break;
186
187 case task_management::Task::BROWSER:
188 last_browser_process_cpu_ = cpu_usage;
189 last_browser_process_memory_ = memory_usage >= 0 ? memory_usage : 0;
190 break;
191
192 case task_management::Task::GPU:
193 last_gpu_process_cpu_ = cpu_usage;
194 last_gpu_process_memory_ = memory_usage >= 0 ? memory_usage : 0;
195 break;
196
197 default:
198 // Other tasks types will be reported using Rappor.
199 TaskRecord* task_data = nullptr;
200 auto itr = task_records_.find(id);
201 if (itr == task_records_.end()) {
202 task_data = new TaskRecord(id);
203 task_records_[id] = make_scoped_ptr(task_data);
204 } else {
205 task_data = itr->second.get();
206 }
207
208 DCHECK_EQ(task_data->id, id);
209 task_data->task_name_for_rappor =
210 observed_task_manager()->GetTaskNameForRappor(id);
211 task_data->cpu_percent = cpu_usage;
212 task_data->memory_bytes = memory_usage;
213 task_data->is_background =
214 observed_task_manager()->IsTaskOnBackgroundedProcess(id);
215
216 // Push only valid or useful data to both priority queues. They might
217 // end up having more records than |kTopConsumerCount|, that's fine.
218 // We'll take care of that next.
219 if (task_data->cpu_percent > 0)
220 records_by_cpu_queue.push(task_data);
221 if (task_data->memory_bytes > 0)
222 records_by_memory_queue.push(task_data);
223 }
224 }
225
226 // Sort the |kTopConsumersCount| task records by their CPU and memory usage.
227 while (!records_by_cpu_queue.empty() &&
228 task_records_by_cpu_.size() < kTopConsumersCount) {
229 task_records_by_cpu_.push_back(records_by_cpu_queue.top());
230 records_by_cpu_queue.pop();
231 }
232
233 while (!records_by_memory_queue.empty() &&
234 task_records_by_memory_.size() < kTopConsumersCount) {
235 task_records_by_memory_.push_back(records_by_memory_queue.top());
236 records_by_memory_queue.pop();
237 }
238 }
239
240 // static
241 const size_t ResourceReporter::kTopConsumersCount = 10U;
242
243 ResourceReporter::ResourceReporter()
244 : TaskManagerObserver(base::TimeDelta::FromSeconds(kRefreshIntervalSeconds),
245 task_management::REFRESH_TYPE_CPU |
246 task_management::REFRESH_TYPE_MEMORY |
247 task_management::REFRESH_TYPE_PRIORITY),
248 system_cpu_cores_range_(GetCurrentSystemCpuCoresRange()) {
249 }
250
251 // static
252 scoped_ptr<rappor::Sample> ResourceReporter::CreateRapporSample(
253 rappor::RapporService* rappor_service,
254 const ResourceReporter::TaskRecord& task_record) {
255 scoped_ptr<rappor::Sample> sample(rappor_service->CreateSample(
256 rappor::UMA_RAPPOR_TYPE));
257 sample->SetStringField(kRapporTaskStringField,
258 task_record.task_name_for_rappor);
259 sample->SetFlagsField(kRapporPriorityFlagsField,
260 task_record.is_background ?
261 GET_ENUM_VAL(TaskProcessPriority::BACKGROUND) :
262 GET_ENUM_VAL(TaskProcessPriority::FOREGROUND),
263 GET_ENUM_VAL(TaskProcessPriority::PRIORITIES_NUM));
264 return sample.Pass();
265 }
266
267 // static
268 ResourceReporter::CpuUsageRange
269 ResourceReporter::GetCpuUsageRange(double cpu) {
270 if (cpu > 60.0)
271 return CpuUsageRange::RANGE_ABOVE_60_PERCENT;
272 if (cpu > 30.0)
273 return CpuUsageRange::RANGE_30_TO_60_PERCENT;
274 if (cpu > 10.0)
275 return CpuUsageRange::RANGE_10_TO_30_PERCENT;
276
277 return CpuUsageRange::RANGE_0_TO_10_PERCENT;
278 }
279
280 // static
281 ResourceReporter::MemoryUsageRange
282 ResourceReporter::GetMemoryUsageRange(int64_t memory_in_bytes) {
283 if (memory_in_bytes > kMemory1GB)
284 return MemoryUsageRange::RANGE_ABOVE_1_GB;
285 if (memory_in_bytes > kMemory800MB)
286 return MemoryUsageRange::RANGE_800_TO_1_GB;
287 if (memory_in_bytes > kMemory600MB)
288 return MemoryUsageRange::RANGE_600_TO_800_MB;
289 if (memory_in_bytes > kMemory400MB)
290 return MemoryUsageRange::RANGE_400_TO_600_MB;
291 if (memory_in_bytes > kMemory200MB)
292 return MemoryUsageRange::RANGE_200_TO_400_MB;
293
294 return MemoryUsageRange::RANGE_0_TO_200_MB;
295 }
296
297 // static
298 ResourceReporter::CpuCoresNumberRange
299 ResourceReporter::GetCurrentSystemCpuCoresRange() {
300 const int cpus = base::SysInfo::NumberOfProcessors();
301
302 if (cpus > 16)
303 return CpuCoresNumberRange::RANGE_CORES_ABOVE_16_CORES;
304 if (cpus > 8)
305 return CpuCoresNumberRange::RANGE_CORES_9_TO_16_CORES;
306 if (cpus > 4)
307 return CpuCoresNumberRange::RANGE_CORES_5_TO_8_CORES;
308 if (cpus > 2)
309 return CpuCoresNumberRange::RANGE_CORES_3_TO_4_CORES;
310 if (cpus == 2)
311 return CpuCoresNumberRange::RANGE_CORES_2_CORES;
312 if (cpus == 1)
313 return CpuCoresNumberRange::RANGE_CORES_1_CORE;
314
315 NOTREACHED();
316 return CpuCoresNumberRange::RANGE_CORES_NA;
317 }
318
319 const ResourceReporter::TaskRecord* ResourceReporter::SampleTaskByCpu() const {
320 // Perform a weighted random sampling taking the tasks' CPU usage as their
321 // weights to randomly select one of them to be reported by Rappor. The higher
322 // the CPU usage, the higher the chance that the task will be selected.
323 // See https://en.wikipedia.org/wiki/Reservoir_sampling.
324 TaskRecord* sampled_task = nullptr;
325 double cpu_weights_sum = 0;
326 for (const auto& task_data : task_records_by_cpu_) {
327 if ((base::RandDouble() * (cpu_weights_sum + task_data->cpu_percent)) >=
328 cpu_weights_sum) {
329 sampled_task = task_data;
330 }
331 cpu_weights_sum += task_data->cpu_percent;
332 }
333
334 return sampled_task;
335 }
336
337 const ResourceReporter::TaskRecord*
338 ResourceReporter::SampleTaskByMemory() const {
339 // Perform a weighted random sampling taking the tasks' memory usage as their
340 // weights to randomly select one of them to be reported by Rappor. The higher
341 // the memory usage, the higher the chance that the task will be selected.
342 // See https://en.wikipedia.org/wiki/Reservoir_sampling.
343 TaskRecord* sampled_task = nullptr;
344 int64_t memory_weights_sum = 0;
345 for (const auto& task_data : task_records_by_memory_) {
346 if ((base::RandDouble() * (memory_weights_sum + task_data->memory_bytes)) >=
347 memory_weights_sum) {
348 sampled_task = task_data;
349 }
350 memory_weights_sum += task_data->memory_bytes;
351 }
352
353 return sampled_task;
354 }
355
356 void ResourceReporter::OnMemoryPressure(
357 MemoryPressureLevel memory_pressure_level) {
358 if (memory_pressure_level >=
359 MemoryPressureLevel::MEMORY_PRESSURE_LEVEL_MODERATE) {
360 // Report browser and GPU processes usage using UMA histograms.
361 UMA_HISTOGRAM_ENUMERATION(
362 "ResourceReporter.BrowserProcess.CpuUsage",
363 GET_ENUM_VAL(GetCpuUsageRange(last_browser_process_cpu_)),
364 GET_ENUM_VAL(CpuUsageRange::CPU_RANGES_NUM));
365 UMA_HISTOGRAM_ENUMERATION(
366 "ResourceReporter.BrowserProcess.MemoryUsage",
367 GET_ENUM_VAL(GetMemoryUsageRange(last_browser_process_memory_)),
368 GET_ENUM_VAL(MemoryUsageRange::MEMORY_RANGES_NUM));
369 UMA_HISTOGRAM_ENUMERATION(
370 "ResourceReporter.GpuProcess.CpuUsage",
371 GET_ENUM_VAL(GetCpuUsageRange(last_gpu_process_cpu_)),
372 GET_ENUM_VAL(CpuUsageRange::CPU_RANGES_NUM));
373 UMA_HISTOGRAM_ENUMERATION(
374 "ResourceReporter.GpuProcess.MemoryUsage",
375 GET_ENUM_VAL(GetMemoryUsageRange(last_gpu_process_memory_)),
376 GET_ENUM_VAL(MemoryUsageRange::MEMORY_RANGES_NUM));
377
378 // For the rest of tasks, report them using Rappor.
379 auto rappor_service = g_browser_process->rappor_service();
380 if (!rappor_service)
381 return;
382
383 // We only record Rappor samples only if it's the first ever moderate or
384 // critical memory pressure event we receive, or it has been more than
385 // |kMinimumTimeBetweenReportsInMs| since the last time we recorded samples.
386 if (!have_seen_first_memory_pressure_event_) {
387 have_seen_first_memory_pressure_event_ = true;
388 } else if ((base::TimeTicks::Now() - last_memory_pressure_event_time_) <
389 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenReportsInMs)) {
390 return;
391 }
392
393 last_memory_pressure_event_time_ = base::TimeTicks::Now();
394
395 // Use weighted random sampling to select a task to report in the CPU
396 // metric.
397 const TaskRecord* sampled_cpu_task = SampleTaskByCpu();
398 if (sampled_cpu_task) {
399 scoped_ptr<rappor::Sample> cpu_sample(
400 CreateRapporSample(rappor_service, *sampled_cpu_task));
401 cpu_sample->SetFlagsField(
402 kRapporNumCoresRangeFlagsField,
403 GET_ENUM_VAL(system_cpu_cores_range_),
404 GET_ENUM_VAL(CpuCoresNumberRange::CORES_RANGES_NUM));
405 cpu_sample->SetFlagsField(
406 kRapporUsageRangeFlagsField,
407 GET_ENUM_VAL(GetCpuUsageRange(sampled_cpu_task->cpu_percent)),
408 GET_ENUM_VAL(CpuUsageRange::CPU_RANGES_NUM));
409 rappor_service->RecordSampleObj(kCpuRapporMetric, cpu_sample.Pass());
410 }
411
412 // Use weighted random sampling to select a task to report in the memory
413 // metric.
414 const TaskRecord* sampled_memory_task = SampleTaskByMemory();
415 if (sampled_memory_task) {
416 scoped_ptr<rappor::Sample> memory_sample(
417 CreateRapporSample(rappor_service, *sampled_memory_task));
418 memory_sample->SetFlagsField(
419 kRapporUsageRangeFlagsField,
420 GET_ENUM_VAL(GetMemoryUsageRange(sampled_memory_task->memory_bytes)),
421 GET_ENUM_VAL(MemoryUsageRange::MEMORY_RANGES_NUM));
422 rappor_service->RecordSampleObj(kMemoryRapporMetric,
423 memory_sample.Pass());
424 }
425 }
426 }
427
428 } // namespace chromeos
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698