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

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: Turn off ResourceReporter on task_management CrOs browser_tests. 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 have_seen_first_task_manager_refresh_ = true;
160
161 // A priority queue to sort the task records by their |cpu|. Greatest |cpu|
162 // first.
163 std::priority_queue<TaskRecord*,
164 std::vector<TaskRecord*>,
165 TaskRecordCpuLessThan> records_by_cpu_queue;
166 // A priority queue to sort the task records by their |memory|. Greatest
167 // |memory| first.
168 std::priority_queue<TaskRecord*,
169 std::vector<TaskRecord*>,
170 TaskRecordMemoryLessThan> records_by_memory_queue;
171 task_records_by_cpu_.clear();
172 task_records_by_cpu_.reserve(kTopConsumersCount);
173 task_records_by_memory_.clear();
174 task_records_by_memory_.reserve(kTopConsumersCount);
175
176 for (const auto& id : task_ids) {
177 const double cpu_usage = observed_task_manager()->GetCpuUsage(id);
178 const int64_t memory_usage =
179 observed_task_manager()->GetPhysicalMemoryUsage(id);
180
181 // Browser and GPU processes are reported later using UMA histograms as they
182 // don't have any privacy issues.
183 const auto task_type = observed_task_manager()->GetType(id);
184 switch (task_type) {
185 case task_management::Task::UNKNOWN:
186 case task_management::Task::ZYGOTE:
187 break;
188
189 case task_management::Task::BROWSER:
190 last_browser_process_cpu_ = cpu_usage;
191 last_browser_process_memory_ = memory_usage >= 0 ? memory_usage : 0;
192 break;
193
194 case task_management::Task::GPU:
195 last_gpu_process_cpu_ = cpu_usage;
196 last_gpu_process_memory_ = memory_usage >= 0 ? memory_usage : 0;
197 break;
198
199 default:
200 // Other tasks types will be reported using Rappor.
201 TaskRecord* task_data = nullptr;
202 auto itr = task_records_.find(id);
203 if (itr == task_records_.end()) {
204 task_data = new TaskRecord(id);
205 task_records_[id] = make_scoped_ptr(task_data);
206 } else {
207 task_data = itr->second.get();
208 }
209
210 DCHECK_EQ(task_data->id, id);
211 task_data->task_name_for_rappor =
212 observed_task_manager()->GetTaskNameForRappor(id);
213 task_data->cpu_percent = cpu_usage;
214 task_data->memory_bytes = memory_usage;
215 task_data->is_background =
216 observed_task_manager()->IsTaskOnBackgroundedProcess(id);
217
218 // Push only valid or useful data to both priority queues. They might
219 // end up having more records than |kTopConsumerCount|, that's fine.
220 // We'll take care of that next.
221 if (task_data->cpu_percent > 0)
222 records_by_cpu_queue.push(task_data);
223 if (task_data->memory_bytes > 0)
224 records_by_memory_queue.push(task_data);
225 }
226 }
227
228 // Sort the |kTopConsumersCount| task records by their CPU and memory usage.
229 while (!records_by_cpu_queue.empty() &&
230 task_records_by_cpu_.size() < kTopConsumersCount) {
231 task_records_by_cpu_.push_back(records_by_cpu_queue.top());
232 records_by_cpu_queue.pop();
233 }
234
235 while (!records_by_memory_queue.empty() &&
236 task_records_by_memory_.size() < kTopConsumersCount) {
237 task_records_by_memory_.push_back(records_by_memory_queue.top());
238 records_by_memory_queue.pop();
239 }
240 }
241
242 // static
243 const size_t ResourceReporter::kTopConsumersCount = 10U;
244
245 ResourceReporter::ResourceReporter()
246 : TaskManagerObserver(base::TimeDelta::FromSeconds(kRefreshIntervalSeconds),
247 task_management::REFRESH_TYPE_CPU |
248 task_management::REFRESH_TYPE_MEMORY |
249 task_management::REFRESH_TYPE_PRIORITY),
250 system_cpu_cores_range_(GetCurrentSystemCpuCoresRange()) {
251 }
252
253 // static
254 scoped_ptr<rappor::Sample> ResourceReporter::CreateRapporSample(
255 rappor::RapporService* rappor_service,
256 const ResourceReporter::TaskRecord& task_record) {
257 scoped_ptr<rappor::Sample> sample(rappor_service->CreateSample(
258 rappor::UMA_RAPPOR_TYPE));
259 sample->SetStringField(kRapporTaskStringField,
260 task_record.task_name_for_rappor);
261 sample->SetFlagsField(kRapporPriorityFlagsField,
262 task_record.is_background ?
263 GET_ENUM_VAL(TaskProcessPriority::BACKGROUND) :
264 GET_ENUM_VAL(TaskProcessPriority::FOREGROUND),
265 GET_ENUM_VAL(TaskProcessPriority::NUM_PRIORITIES));
266 return sample.Pass();
267 }
268
269 // static
270 ResourceReporter::CpuUsageRange
271 ResourceReporter::GetCpuUsageRange(double cpu) {
272 if (cpu > 60.0)
273 return CpuUsageRange::RANGE_ABOVE_60_PERCENT;
274 if (cpu > 30.0)
275 return CpuUsageRange::RANGE_30_TO_60_PERCENT;
276 if (cpu > 10.0)
277 return CpuUsageRange::RANGE_10_TO_30_PERCENT;
278
279 return CpuUsageRange::RANGE_0_TO_10_PERCENT;
280 }
281
282 // static
283 ResourceReporter::MemoryUsageRange
284 ResourceReporter::GetMemoryUsageRange(int64_t memory_in_bytes) {
285 if (memory_in_bytes > kMemory1GB)
286 return MemoryUsageRange::RANGE_ABOVE_1_GB;
287 if (memory_in_bytes > kMemory800MB)
288 return MemoryUsageRange::RANGE_800_TO_1_GB;
289 if (memory_in_bytes > kMemory600MB)
290 return MemoryUsageRange::RANGE_600_TO_800_MB;
291 if (memory_in_bytes > kMemory400MB)
292 return MemoryUsageRange::RANGE_400_TO_600_MB;
293 if (memory_in_bytes > kMemory200MB)
294 return MemoryUsageRange::RANGE_200_TO_400_MB;
295
296 return MemoryUsageRange::RANGE_0_TO_200_MB;
297 }
298
299 // static
300 ResourceReporter::CpuCoresNumberRange
301 ResourceReporter::GetCurrentSystemCpuCoresRange() {
302 const int cpus = base::SysInfo::NumberOfProcessors();
303
304 if (cpus > 16)
305 return CpuCoresNumberRange::RANGE_ABOVE_16_CORES;
306 if (cpus > 8)
307 return CpuCoresNumberRange::RANGE_9_TO_16_CORES;
308 if (cpus > 4)
309 return CpuCoresNumberRange::RANGE_5_TO_8_CORES;
310 if (cpus > 2)
311 return CpuCoresNumberRange::RANGE_3_TO_4_CORES;
312 if (cpus == 2)
313 return CpuCoresNumberRange::RANGE_2_CORES;
314 if (cpus == 1)
315 return CpuCoresNumberRange::RANGE_1_CORE;
316
317 NOTREACHED();
318 return CpuCoresNumberRange::RANGE_NA;
319 }
320
321 const ResourceReporter::TaskRecord* ResourceReporter::SampleTaskByCpu() const {
322 // Perform a weighted random sampling taking the tasks' CPU usage as their
323 // weights to randomly select one of them to be reported by Rappor. The higher
324 // the CPU usage, the higher the chance that the task will be selected.
325 // See https://en.wikipedia.org/wiki/Reservoir_sampling.
326 TaskRecord* sampled_task = nullptr;
327 double cpu_weights_sum = 0;
328 for (const auto& task_data : task_records_by_cpu_) {
329 if ((base::RandDouble() * (cpu_weights_sum + task_data->cpu_percent)) >=
330 cpu_weights_sum) {
331 sampled_task = task_data;
332 }
333 cpu_weights_sum += task_data->cpu_percent;
334 }
335
336 return sampled_task;
337 }
338
339 const ResourceReporter::TaskRecord*
340 ResourceReporter::SampleTaskByMemory() const {
341 // Perform a weighted random sampling taking the tasks' memory usage as their
342 // weights to randomly select one of them to be reported by Rappor. The higher
343 // the memory usage, the higher the chance that the task will be selected.
344 // See https://en.wikipedia.org/wiki/Reservoir_sampling.
345 TaskRecord* sampled_task = nullptr;
346 int64_t memory_weights_sum = 0;
347 for (const auto& task_data : task_records_by_memory_) {
348 if ((base::RandDouble() * (memory_weights_sum + task_data->memory_bytes)) >=
349 memory_weights_sum) {
350 sampled_task = task_data;
351 }
352 memory_weights_sum += task_data->memory_bytes;
353 }
354
355 return sampled_task;
356 }
357
358 void ResourceReporter::OnMemoryPressure(
359 MemoryPressureLevel memory_pressure_level) {
360 if (have_seen_first_task_manager_refresh_ &&
361 memory_pressure_level >=
362 MemoryPressureLevel::MEMORY_PRESSURE_LEVEL_MODERATE) {
363 // Report browser and GPU processes usage using UMA histograms.
364 UMA_HISTOGRAM_ENUMERATION(
365 "ResourceReporter.BrowserProcess.CpuUsage",
366 GET_ENUM_VAL(GetCpuUsageRange(last_browser_process_cpu_)),
367 GET_ENUM_VAL(CpuUsageRange::NUM_RANGES));
368 UMA_HISTOGRAM_ENUMERATION(
369 "ResourceReporter.BrowserProcess.MemoryUsage",
370 GET_ENUM_VAL(GetMemoryUsageRange(last_browser_process_memory_)),
371 GET_ENUM_VAL(MemoryUsageRange::NUM_RANGES));
372 UMA_HISTOGRAM_ENUMERATION(
373 "ResourceReporter.GpuProcess.CpuUsage",
374 GET_ENUM_VAL(GetCpuUsageRange(last_gpu_process_cpu_)),
375 GET_ENUM_VAL(CpuUsageRange::NUM_RANGES));
376 UMA_HISTOGRAM_ENUMERATION(
377 "ResourceReporter.GpuProcess.MemoryUsage",
378 GET_ENUM_VAL(GetMemoryUsageRange(last_gpu_process_memory_)),
379 GET_ENUM_VAL(MemoryUsageRange::NUM_RANGES));
380
381 // For the rest of tasks, report them using Rappor.
382 auto rappor_service = g_browser_process->rappor_service();
383 if (!rappor_service)
384 return;
385
386 // We only record Rappor samples only if it's the first ever moderate or
387 // critical memory pressure event we receive, or it has been more than
388 // |kMinimumTimeBetweenReportsInMs| since the last time we recorded samples.
389 if (!have_seen_first_memory_pressure_event_) {
390 have_seen_first_memory_pressure_event_ = true;
391 } else if ((base::TimeTicks::Now() - last_memory_pressure_event_time_) <
392 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenReportsInMs)) {
393 return;
394 }
395
396 last_memory_pressure_event_time_ = base::TimeTicks::Now();
397
398 // Use weighted random sampling to select a task to report in the CPU
399 // metric.
400 const TaskRecord* sampled_cpu_task = SampleTaskByCpu();
401 if (sampled_cpu_task) {
402 scoped_ptr<rappor::Sample> cpu_sample(
403 CreateRapporSample(rappor_service, *sampled_cpu_task));
404 cpu_sample->SetFlagsField(kRapporNumCoresRangeFlagsField,
405 GET_ENUM_VAL(system_cpu_cores_range_),
406 GET_ENUM_VAL(CpuCoresNumberRange::NUM_RANGES));
407 cpu_sample->SetFlagsField(
408 kRapporUsageRangeFlagsField,
409 GET_ENUM_VAL(GetCpuUsageRange(sampled_cpu_task->cpu_percent)),
410 GET_ENUM_VAL(CpuUsageRange::NUM_RANGES));
411 rappor_service->RecordSampleObj(kCpuRapporMetric, cpu_sample.Pass());
412 }
413
414 // Use weighted random sampling to select a task to report in the memory
415 // metric.
416 const TaskRecord* sampled_memory_task = SampleTaskByMemory();
417 if (sampled_memory_task) {
418 scoped_ptr<rappor::Sample> memory_sample(
419 CreateRapporSample(rappor_service, *sampled_memory_task));
420 memory_sample->SetFlagsField(
421 kRapporUsageRangeFlagsField,
422 GET_ENUM_VAL(GetMemoryUsageRange(sampled_memory_task->memory_bytes)),
423 GET_ENUM_VAL(MemoryUsageRange::NUM_RANGES));
424 rappor_service->RecordSampleObj(kMemoryRapporMetric,
425 memory_sample.Pass());
426 }
427 }
428 }
429
430 } // namespace chromeos
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698