blob: 9b0bb344143c4b8541ebe37e7e504e0a6351cad1 [file] [log] [blame]
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "collectors/cpu_usage_collector.h"
18
19#include <base/bind.h>
20#include <base/files/file_path.h>
21#include <base/files/file_util.h>
22#include <base/message_loop/message_loop.h>
23#include <base/strings/string_number_conversions.h>
24#include <base/strings/string_split.h>
25#include <base/strings/string_util.h>
26#include <base/sys_info.h>
27
28#include "metrics/metrics_library.h"
29
30namespace {
31
32const char kCpuUsagePercent[] = "Platform.CpuUsage.Percent";
33const char kMetricsProcStatFileName[] = "/proc/stat";
34const int kMetricsProcStatFirstLineItemsCount = 11;
35
36// Collect every minute.
37const int kCollectionIntervalSecs = 60;
38
39} // namespace
40
41using base::TimeDelta;
42
43CpuUsageCollector::CpuUsageCollector(MetricsLibraryInterface* metrics_library) {
44 CHECK(metrics_library);
45 metrics_lib_ = metrics_library;
46 collect_interval_ = TimeDelta::FromSeconds(kCollectionIntervalSecs);
47}
48
49void CpuUsageCollector::Init() {
50 num_cpu_ = base::SysInfo::NumberOfProcessors();
51
52 // Get ticks per second (HZ) on this system.
53 // Sysconf cannot fail, so no sanity checks are needed.
54 ticks_per_second_ = sysconf(_SC_CLK_TCK);
55 CHECK_GT(ticks_per_second_, uint64_t(0))
56 << "Number of ticks per seconds should be positive.";
57
58 latest_cpu_use_ = GetCumulativeCpuUse();
59}
60
61void CpuUsageCollector::CollectCallback() {
62 Collect();
63 Schedule();
64}
65
66void CpuUsageCollector::Schedule() {
67 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
68 base::Bind(&CpuUsageCollector::CollectCallback, base::Unretained(this)),
69 collect_interval_);
70}
71
72void CpuUsageCollector::Collect() {
73 TimeDelta cpu_use = GetCumulativeCpuUse();
74 TimeDelta diff_per_cpu = (cpu_use - latest_cpu_use_) / num_cpu_;
75 latest_cpu_use_ = cpu_use;
76
77 // Report the cpu usage as a percentage of the total cpu usage possible.
78 int percent_use = diff_per_cpu.InMilliseconds() * 100 /
79 (kCollectionIntervalSecs * 1000);
80
81 metrics_lib_->SendEnumToUMA(kCpuUsagePercent, percent_use, 101);
82}
83
84TimeDelta CpuUsageCollector::GetCumulativeCpuUse() {
85 base::FilePath proc_stat_path(kMetricsProcStatFileName);
86 std::string proc_stat_string;
87 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
88 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
89 return TimeDelta();
90 }
91
92 uint64_t user_ticks, user_nice_ticks, system_ticks;
93 if (!ParseProcStat(proc_stat_string, &user_ticks, &user_nice_ticks,
94 &system_ticks)) {
95 return TimeDelta();
96 }
97
98 uint64_t total = user_ticks + user_nice_ticks + system_ticks;
99 return TimeDelta::FromMicroseconds(
100 total * 1000 * 1000 / ticks_per_second_);
101}
102
103bool CpuUsageCollector::ParseProcStat(const std::string& stat_content,
104 uint64_t *user_ticks,
105 uint64_t *user_nice_ticks,
106 uint64_t *system_ticks) {
Alex Vakulenkoea05ff92016-01-20 07:53:57 -0800107 std::vector<std::string> proc_stat_lines = base::SplitString(
108 stat_content, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800109 if (proc_stat_lines.empty()) {
110 LOG(WARNING) << "No lines found in " << kMetricsProcStatFileName;
111 return false;
112 }
Alex Vakulenkoea05ff92016-01-20 07:53:57 -0800113 std::vector<std::string> proc_stat_totals =
114 base::SplitString(proc_stat_lines[0], base::kWhitespaceASCII,
115 base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800116
117 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
118 proc_stat_totals[0] != "cpu" ||
119 !base::StringToUint64(proc_stat_totals[1], user_ticks) ||
120 !base::StringToUint64(proc_stat_totals[2], user_nice_ticks) ||
121 !base::StringToUint64(proc_stat_totals[3], system_ticks)) {
122 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
123 return false;
124 }
125 return true;
126}