blob: 9eb6802132d136f9b93d9d8b39b46739136c5e02 [file] [log] [blame]
Bertrand SIMONNET52e5b992015-08-10 15:18:00 -07001/*
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 */
Darin Petkov65b01462010-04-14 13:32:20 -070016
Bertrand SIMONNET4b915ae2015-07-28 15:38:14 -070017#include "metrics_daemon.h"
Darin Petkov65b01462010-04-14 13:32:20 -070018
Steve Funge86591e2014-12-01 13:38:21 -080019#include <sysexits.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -070020#include <time.h>
Darin Petkov65b01462010-04-14 13:32:20 -070021
Bertrand SIMONNET4b915ae2015-07-28 15:38:14 -070022#include <base/bind.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080023#include <base/files/file_path.h>
Ben Chan51bf92a2014-09-05 08:21:06 -070024#include <base/files/file_util.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080025#include <base/hash.h>
Darin Petkov65b01462010-04-14 13:32:20 -070026#include <base/logging.h>
Ben Chan2e6543d2014-02-05 23:26:25 -080027#include <base/strings/string_number_conversions.h>
28#include <base/strings/string_split.h>
29#include <base/strings/string_util.h>
30#include <base/strings/stringprintf.h>
Bertrand SIMONNET26993622015-08-20 14:08:41 -070031#include <cutils/properties.h>
Steve Funge86591e2014-12-01 13:38:21 -080032#include <dbus/dbus.h>
33#include <dbus/message.h>
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -070034
35#include "constants.h"
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -070036#include "uploader/upload_service.h"
Darin Petkov65b01462010-04-14 13:32:20 -070037
Ben Chan2e6543d2014-02-05 23:26:25 -080038using base::FilePath;
39using base::StringPrintf;
Darin Petkovf27f0362010-06-04 13:14:19 -070040using base::Time;
41using base::TimeDelta;
42using base::TimeTicks;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080043using chromeos_metrics::PersistentInteger;
Luigi Semenzato8accd332011-05-17 16:37:18 -070044using std::map;
Darin Petkov38d5cb02010-06-24 12:10:26 -070045using std::string;
Luigi Semenzato8accd332011-05-17 16:37:18 -070046using std::vector;
47
Daniel Eratc83975a2014-04-04 08:53:44 -070048namespace {
Darin Petkovf27f0362010-06-04 13:14:19 -070049
Daniel Eratc83975a2014-04-04 08:53:44 -070050const char kCrashReporterInterface[] = "org.chromium.CrashReporter";
51const char kCrashReporterUserCrashSignal[] = "UserCrash";
Steve Funge86591e2014-12-01 13:38:21 -080052const char kCrashReporterMatchRule[] =
53 "type='signal',interface='%s',path='/',member='%s'";
Darin Petkov41e06232010-05-03 16:45:37 -070054
Daniel Eratc83975a2014-04-04 08:53:44 -070055const int kSecondsPerMinute = 60;
56const int kMinutesPerHour = 60;
57const int kHoursPerDay = 24;
58const int kMinutesPerDay = kHoursPerDay * kMinutesPerHour;
59const int kSecondsPerDay = kSecondsPerMinute * kMinutesPerDay;
60const int kDaysPerWeek = 7;
61const int kSecondsPerWeek = kSecondsPerDay * kDaysPerWeek;
Darin Petkov41e06232010-05-03 16:45:37 -070062
Daniel Eratc83975a2014-04-04 08:53:44 -070063// Interval between calls to UpdateStats().
Steve Funge86591e2014-12-01 13:38:21 -080064const uint32_t kUpdateStatsIntervalMs = 300000;
Darin Petkov65b01462010-04-14 13:32:20 -070065
Luigi Semenzatoc5a92342014-02-14 15:05:51 -080066const char kKernelCrashDetectedFile[] = "/var/run/kernel-crash-detected";
Daniel Eratc83975a2014-04-04 08:53:44 -070067const char kUncleanShutdownDetectedFile[] =
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080068 "/var/run/unclean-shutdown-detected";
Ken Mixterccd84c02010-08-16 19:57:13 -070069
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -070070const int kMetricMeminfoInterval = 30; // seconds
71
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070072const char kMetricsProcStatFileName[] = "/proc/stat";
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070073const char kMeminfoFileName[] = "/proc/meminfo";
Bertrand SIMONNET7a964052015-09-29 11:07:24 -070074const char kVmStatFileName[] = "/proc/vmstat";
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070075const int kMetricsProcStatFirstLineItemsCount = 11;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -070076
Luigi Semenzatofb3a8212013-05-07 16:55:00 -070077// Thermal CPU throttling.
78
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070079const char kMetricScaledCpuFrequencyName[] =
Luigi Semenzatofb3a8212013-05-07 16:55:00 -070080 "Platform.CpuFrequencyThermalScaling";
81
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070082} // namespace
83
Luigi Semenzato96360192014-06-04 10:53:35 -070084// Zram sysfs entries.
85
86const char MetricsDaemon::kComprDataSizeName[] = "compr_data_size";
87const char MetricsDaemon::kOrigDataSizeName[] = "orig_data_size";
88const char MetricsDaemon::kZeroPagesName[] = "zero_pages";
89
Luigi Semenzato8accd332011-05-17 16:37:18 -070090// Memory use stats collection intervals. We collect some memory use interval
91// at these intervals after boot, and we stop collecting after the last one,
92// with the assumption that in most cases the memory use won't change much
93// after that.
94static const int kMemuseIntervals[] = {
95 1 * kSecondsPerMinute, // 1 minute mark
96 4 * kSecondsPerMinute, // 5 minute mark
97 25 * kSecondsPerMinute, // 0.5 hour mark
98 120 * kSecondsPerMinute, // 2.5 hour mark
99 600 * kSecondsPerMinute, // 12.5 hour mark
100};
101
Darin Petkovf1e85e42010-06-10 15:59:53 -0700102MetricsDaemon::MetricsDaemon()
Steve Funge86591e2014-12-01 13:38:21 -0800103 : memuse_final_time_(0),
Luigi Semenzato8accd332011-05-17 16:37:18 -0700104 memuse_interval_index_(0),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700105 ticks_per_second_(0),
106 latest_cpu_use_ticks_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700107
Ken Mixter4c5daa42010-08-26 18:35:06 -0700108MetricsDaemon::~MetricsDaemon() {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700109}
110
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700111// static
Luigi Semenzato8accd332011-05-17 16:37:18 -0700112double MetricsDaemon::GetActiveTime() {
113 struct timespec ts;
114 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
115 if (r < 0) {
116 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
117 return 0;
118 } else {
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700119 return ts.tv_sec + static_cast<double>(ts.tv_nsec) / (1000 * 1000 * 1000);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700120 }
121}
122
Steve Funge86591e2014-12-01 13:38:21 -0800123int MetricsDaemon::Run() {
Ken Mixterccd84c02010-08-16 19:57:13 -0700124 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
125 ProcessKernelCrash();
126 }
127
128 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
129 ProcessUncleanShutdown();
130 }
131
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800132 // On OS version change, clear version stats (which are reported daily).
Ben Chanf05ab402014-08-07 00:54:59 -0700133 int32_t version = GetOsVersionHash();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800134 if (version_cycle_->Get() != version) {
135 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800136 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700137 version_cumulative_active_use_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700138 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800139 }
140
Steve Funge86591e2014-12-01 13:38:21 -0800141 return chromeos::DBusDaemon::Run();
Darin Petkov65b01462010-04-14 13:32:20 -0700142}
143
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700144void MetricsDaemon::RunUploaderTest() {
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700145 upload_service_.reset(new UploadService(
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700146 new SystemProfileCache(true, metrics_directory_),
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700147 metrics_lib_,
148 server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700149 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700150 upload_service_->UploadEvent();
151}
152
Ben Chanf05ab402014-08-07 00:54:59 -0700153uint32_t MetricsDaemon::GetOsVersionHash() {
154 static uint32_t cached_version_hash = 0;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800155 static bool version_hash_is_cached = false;
156 if (version_hash_is_cached)
157 return cached_version_hash;
158 version_hash_is_cached = true;
Bertrand SIMONNET26993622015-08-20 14:08:41 -0700159
160 char version[PROPERTY_VALUE_MAX];
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700161 // The version might not be set for development devices. In this case, use the
162 // zero version.
Bertrand SIMONNET26993622015-08-20 14:08:41 -0700163 property_get(metrics::kProductVersionProperty, version,
164 metrics::kDefaultVersion);
165
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700166 cached_version_hash = base::Hash(version);
167 if (testing_) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800168 cached_version_hash = 42; // return any plausible value for the hash
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800169 }
170 return cached_version_hash;
171}
172
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700173void MetricsDaemon::Init(bool testing,
174 bool uploader_active,
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700175 bool dbus_enabled,
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700176 MetricsLibraryInterface* metrics_lib,
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700177 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700178 const string& scaling_max_freq_path,
Steve Fung67906c62014-10-06 15:15:30 -0700179 const string& cpuinfo_max_freq_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700180 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700181 const string& server,
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700182 const base::FilePath& metrics_directory) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700183 CHECK(metrics_lib);
Darin Petkov65b01462010-04-14 13:32:20 -0700184 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800185 uploader_active_ = uploader_active;
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700186 dbus_enabled_ = dbus_enabled;
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700187 metrics_directory_ = metrics_directory;
Darin Petkovfc91b422010-05-12 13:05:45 -0700188 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700189
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700190 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700191 server_ = server;
Steve Fung67906c62014-10-06 15:15:30 -0700192
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700193 // Get ticks per second (HZ) on this system.
194 // Sysconf cannot fail, so no sanity checks are needed.
195 ticks_per_second_ = sysconf(_SC_CLK_TCK);
196
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700197 daily_active_use_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700198 new PersistentInteger("Platform.UseTime.PerDay"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700199 version_cumulative_active_use_.reset(
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700200 new PersistentInteger("Platform.CumulativeUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700201 version_cumulative_cpu_use_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700202 new PersistentInteger("Platform.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700203
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800204 kernel_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700205 new PersistentInteger("Platform.KernelCrashInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800206 unclean_shutdown_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700207 new PersistentInteger("Platform.UncleanShutdownInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800208 user_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700209 new PersistentInteger("Platform.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700210
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800211 any_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700212 new PersistentInteger("Platform.AnyCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800213 any_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700214 new PersistentInteger("Platform.AnyCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800215 user_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700216 new PersistentInteger("Platform.UserCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800217 user_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700218 new PersistentInteger("Platform.UserCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800219 kernel_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700220 new PersistentInteger("Platform.KernelCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800221 kernel_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700222 new PersistentInteger("Platform.KernelCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800223 kernel_crashes_version_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700224 new PersistentInteger("Platform.KernelCrashesSinceUpdate"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800225 unclean_shutdowns_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700226 new PersistentInteger("Platform.UncleanShutdown.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800227 unclean_shutdowns_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700228 new PersistentInteger("Platform.UncleanShutdowns.PerWeek"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700229
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800230 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
231 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
232 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800233
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700234 scaling_max_freq_path_ = scaling_max_freq_path;
235 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700236 disk_usage_collector_.reset(new DiskUsageCollector(metrics_lib_));
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700237 averaged_stats_collector_.reset(
238 new AveragedStatisticsCollector(metrics_lib_, diskstats_path,
239 kVmStatFileName));
Steve Funge86591e2014-12-01 13:38:21 -0800240}
241
242int MetricsDaemon::OnInit() {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700243 int return_code = dbus_enabled_ ? chromeos::DBusDaemon::OnInit() :
244 chromeos::Daemon::OnInit();
Steve Funge86591e2014-12-01 13:38:21 -0800245 if (return_code != EX_OK)
246 return return_code;
247
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700248 StatsReporterInit();
249
250 // Start collecting meminfo stats.
251 ScheduleMeminfoCallback(kMetricMeminfoInterval);
252 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
253 ScheduleMemuseCallback(kMemuseIntervals[0]);
254
Steve Funge86591e2014-12-01 13:38:21 -0800255 if (testing_)
256 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700257
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700258 if (dbus_enabled_) {
259 bus_->AssertOnDBusThread();
260 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700261
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700262 if (bus_->is_connected()) {
263 const std::string match_rule =
264 base::StringPrintf(kCrashReporterMatchRule,
265 kCrashReporterInterface,
266 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700267
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700268 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700269
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700270 DBusError error;
271 dbus_error_init(&error);
272 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700273
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700274 if (dbus_error_is_set(&error)) {
275 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
276 << error.name << ": " << error.message;
277 return EX_SOFTWARE;
278 }
279 } else {
280 LOG(ERROR) << "DBus isn't connected.";
281 return EX_UNAVAILABLE;
Steve Funge86591e2014-12-01 13:38:21 -0800282 }
Darin Petkov703ec972010-04-27 11:02:18 -0700283 }
284
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700285 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
286 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
287 base::Unretained(this)),
288 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
289
Steve Funge86591e2014-12-01 13:38:21 -0800290 if (uploader_active_) {
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700291 upload_service_.reset(
292 new UploadService(new SystemProfileCache(), metrics_lib_, server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700293 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700294 }
Steve Funge86591e2014-12-01 13:38:21 -0800295
296 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700297}
298
Steve Funge86591e2014-12-01 13:38:21 -0800299void MetricsDaemon::OnShutdown(int* return_code) {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700300 if (!testing_ && dbus_enabled_ && bus_->is_connected()) {
Steve Funge86591e2014-12-01 13:38:21 -0800301 const std::string match_rule =
302 base::StringPrintf(kCrashReporterMatchRule,
303 kCrashReporterInterface,
304 kCrashReporterUserCrashSignal);
305
306 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
307
308 DBusError error;
309 dbus_error_init(&error);
310 bus_->RemoveMatch(match_rule, &error);
311
312 if (dbus_error_is_set(&error)) {
313 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
314 << error.name << ": " << error.message;
315 }
316 }
317 chromeos::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700318}
319
Darin Petkov703ec972010-04-27 11:02:18 -0700320// static
321DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
322 DBusMessage* message,
323 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700324 int message_type = dbus_message_get_type(message);
325 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700326 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700327 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
328 }
329
330 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700331 const std::string interface(dbus_message_get_interface(message));
332 const std::string member(dbus_message_get_member(message));
333 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700334
335 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
336
337 DBusMessageIter iter;
338 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700339 if (interface == kCrashReporterInterface) {
340 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700341 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700342 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700343 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700344 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
345 }
346
347 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700348}
349
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700350// One might argue that parts of this should go into
351// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
352
353TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700354 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
355 std::string proc_stat_string;
356 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
357 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
358 return TimeDelta();
359 }
360
361 std::vector<std::string> proc_stat_lines;
362 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
363 if (proc_stat_lines.empty()) {
364 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
365 << ": " << proc_stat_string;
366 return TimeDelta();
367 }
368 std::vector<std::string> proc_stat_totals;
369 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
370
Ben Chanf05ab402014-08-07 00:54:59 -0700371 uint64_t user_ticks, user_nice_ticks, system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700372 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
373 proc_stat_totals[0] != "cpu" ||
374 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
375 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
376 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
377 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
378 return TimeDelta(base::TimeDelta::FromSeconds(0));
379 }
380
Ben Chanf05ab402014-08-07 00:54:59 -0700381 uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700382
383 // Sanity check.
384 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
385 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
386 << " to " << total_cpu_use_ticks;
387 return TimeDelta();
388 }
389
Ben Chanf05ab402014-08-07 00:54:59 -0700390 uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700391 latest_cpu_use_ticks_ = total_cpu_use_ticks;
392 // Use microseconds to avoid significant truncations.
393 return base::TimeDelta::FromMicroseconds(
394 diff * 1000 * 1000 / ticks_per_second_);
395}
396
Darin Petkov1bb904e2010-06-16 15:58:06 -0700397void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700398 // Counts the active time up to now.
399 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700400
401 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700402 SendAndResetCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700403
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800404 any_crashes_daily_count_->Add(1);
405 any_crashes_weekly_count_->Add(1);
406 user_crashes_daily_count_->Add(1);
407 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700408}
409
Darin Petkov38d5cb02010-06-24 12:10:26 -0700410void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700411 // Counts the active time up to now.
412 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700413
414 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700415 SendAndResetCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700416
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800417 any_crashes_daily_count_->Add(1);
418 any_crashes_weekly_count_->Add(1);
419 kernel_crashes_daily_count_->Add(1);
420 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800421
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800422 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700423}
424
Ken Mixterccd84c02010-08-16 19:57:13 -0700425void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700426 // Counts the active time up to now.
427 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700428
429 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700430 SendAndResetCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700431
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800432 unclean_shutdowns_daily_count_->Add(1);
433 unclean_shutdowns_weekly_count_->Add(1);
434 any_crashes_daily_count_->Add(1);
435 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700436}
437
Luigi Semenzato8accd332011-05-17 16:37:18 -0700438bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700439 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800440 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700441 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700442
443 // Deletes the crash-detected file so that the daemon doesn't report
444 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800445 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700446 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700447}
448
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700449void MetricsDaemon::StatsReporterInit() {
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700450 disk_usage_collector_->Schedule();
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700451
452 // Don't start a collection cycle during the first run to avoid delaying the
453 // boot.
454 averaged_stats_collector_->ScheduleWait();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800455}
456
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800457
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700458bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700459 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700460 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800461 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700462 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
463 return false;
464 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800465 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700466 LOG(WARNING) << "no newline in " << value_string;
467 // Continue even though the lack of newline is suspicious.
468 }
469 if (!base::StringToInt(value_string, value)) {
470 LOG(WARNING) << "cannot convert " << value_string << " to int";
471 return false;
472 }
473 return true;
474}
475
476void MetricsDaemon::SendCpuThrottleMetrics() {
477 // |max_freq| is 0 only the first time through.
478 static int max_freq = 0;
479 if (max_freq == -1)
480 // Give up, as sysfs did not report max_freq correctly.
481 return;
482 if (max_freq == 0 || testing_) {
483 // One-time initialization of max_freq. (Every time when testing.)
484 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
485 max_freq = -1;
486 return;
487 }
488 if (max_freq == 0) {
489 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
490 max_freq = -1;
491 return;
492 }
493 if (max_freq % 10000 == 1000) {
494 // Special case: system has turbo mode, and max non-turbo frequency is
495 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
496 // being multiples of (at least) 10 MHz. Although there is no guarantee
497 // of this, it seems a fairly reasonable assumption. Otherwise we should
498 // read scaling_available_frequencies, sort the frequencies, compare the
499 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
500 // hack too, no telling when it will change).
501 max_freq -= 1000;
502 }
503 }
504 int scaled_freq = 0;
505 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
506 return;
507 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
508 // scaled_freq is not the actual turbo frequency. We indicate this situation
509 // with a 101% value.
510 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800511 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700512}
513
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700514void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
515 if (testing_) {
516 return;
517 }
Steve Funge86591e2014-12-01 13:38:21 -0800518 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
519 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
520 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800521 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800522 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700523}
524
Steve Funge86591e2014-12-01 13:38:21 -0800525void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700526 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700527 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800528 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700529 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800530 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700531 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700532 // Make both calls even if the first one fails.
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700533 if (ProcessMeminfo(meminfo_raw)) {
Steve Funge86591e2014-12-01 13:38:21 -0800534 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
535 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800536 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800537 wait);
538 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700539}
540
541// static
542bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700543 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700544 std::string content;
545 if (!base::ReadFileToString(path, &content)) {
546 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
547 return false;
548 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700549 // Remove final newline.
550 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700551 if (!base::StringToUint64(content, value)) {
552 LOG(WARNING) << "invalid integer: " << content;
553 return false;
554 }
555 return true;
556}
557
558bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
559 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700560 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700561 const size_t page_size = 4096;
562
563 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
564 &compr_data_size) ||
565 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
566 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
567 return false;
568 }
569
570 // |orig_data_size| does not include zero-filled pages.
571 orig_data_size += zero_pages * page_size;
572
573 const int compr_data_size_mb = compr_data_size >> 20;
574 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
575 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
576
577 // Report compressed size in megabytes. 100 MB or less has little impact.
578 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
579 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
580 // The compression ratio is multiplied by 100 for better resolution. The
581 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
582 // don't want samples when very little memory is being compressed.
583 if (compr_data_size_mb >= 1) {
584 SendSample("Platform.ZramCompressionRatioPercent",
585 orig_data_size * 100 / compr_data_size, 100, 600, 50);
586 }
587 // The values of interest for zero_pages are between 1MB and 1GB. The units
588 // are number of pages.
589 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
590 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
591
592 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700593}
594
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700595bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700596 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700597 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
598 { "MemFree", "MemFree" },
599 { "Buffers", "Buffers" },
600 { "Cached", "Cached" },
601 // { "SwapCached", "SwapCached" },
602 { "Active", "Active" },
603 { "Inactive", "Inactive" },
604 { "ActiveAnon", "Active(anon)" },
605 { "InactiveAnon", "Inactive(anon)" },
606 { "ActiveFile" , "Active(file)" },
607 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800608 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700609 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800610 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
611 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700612 // { "Dirty", "Dirty" },
613 // { "Writeback", "Writeback" },
614 { "AnonPages", "AnonPages" },
615 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800616 { "Shmem", "Shmem", kMeminfoOp_HistLog },
617 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700618 // { "SReclaimable", "SReclaimable" },
619 // { "SUnreclaim", "SUnreclaim" },
620 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700621 vector<MeminfoRecord> fields(fields_array,
622 fields_array + arraysize(fields_array));
623 if (!FillMeminfo(meminfo_raw, &fields)) {
624 return false;
625 }
626 int total_memory = fields[0].value;
627 if (total_memory == 0) {
628 // this "cannot happen"
629 LOG(WARNING) << "borked meminfo parser";
630 return false;
631 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800632 int swap_total = 0;
633 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700634 // Send all fields retrieved, except total memory.
635 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800636 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
637 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800638 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800639 switch (fields[i].op) {
640 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800641 // report value as percent of total memory
642 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800643 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800644 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800645 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800646 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800647 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800648 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800649 case kMeminfoOp_SwapTotal:
650 swap_total = fields[i].value;
651 case kMeminfoOp_SwapFree:
652 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800653 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700654 }
655 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800656 if (swap_total > 0) {
657 int swap_used = swap_total - swap_free;
658 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800659 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -0700660 SendLinearSample("Platform.MeminfoSwapUsed.Percent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800661 100, 101);
662 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700663 return true;
664}
665
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700666bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
667 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700668 vector<string> lines;
669 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700670
671 // Scan meminfo output and collect field values. Each field name has to
672 // match a meminfo entry (case insensitive) after removing non-alpha
673 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700674 unsigned int ifield = 0;
675 for (unsigned int iline = 0;
676 iline < nlines && ifield < fields->size();
677 iline++) {
678 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700679 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700680 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
681 // Name matches. Parse value and save.
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700682 if (!base::StringToInt(tokens[1], &(*fields)[ifield].value)) {
683 LOG(WARNING) << "Cound not convert " << tokens[1] << " to int";
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700684 return false;
685 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700686 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700687 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700688 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700689 if (ifield < fields->size()) {
690 // End of input reached while scanning.
691 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
692 << " and following";
693 return false;
694 }
695 return true;
696}
697
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800698void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700699 if (testing_) {
700 return;
701 }
Steve Funge86591e2014-12-01 13:38:21 -0800702 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
703 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
704 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700705}
706
707void MetricsDaemon::MemuseCallback() {
708 // Since we only care about active time (i.e. uptime minus sleep time) but
709 // the callbacks are driven by real time (uptime), we check if we should
710 // reschedule this callback due to intervening sleep periods.
711 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800712 // Avoid intervals of less than one second.
713 double remaining_time = ceil(memuse_final_time_ - now);
714 if (remaining_time > 0) {
715 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700716 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800717 // Report stats and advance the measurement interval unless there are
718 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700719 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800720 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
721 double interval = kMemuseIntervals[memuse_interval_index_++];
722 memuse_final_time_ = now + interval;
723 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700724 }
725 }
726}
727
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700728bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700729 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700730 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800731 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700732 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
733 return false;
734 }
735 return ProcessMemuse(meminfo_raw);
736}
737
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700738bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700739 static const MeminfoRecord fields_array[] = {
740 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
741 { "ActiveAnon", "Active(anon)" },
742 { "InactiveAnon", "Inactive(anon)" },
743 };
744 vector<MeminfoRecord> fields(fields_array,
745 fields_array + arraysize(fields_array));
746 if (!FillMeminfo(meminfo_raw, &fields)) {
747 return false;
748 }
749 int total = fields[0].value;
750 int active_anon = fields[1].value;
751 int inactive_anon = fields[2].value;
752 if (total == 0) {
753 // this "cannot happen"
754 LOG(WARNING) << "borked meminfo parser";
755 return false;
756 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800757 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
758 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800759 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -0700760 100, 101);
761 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700762}
763
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800764void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -0700765 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -0700766 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700767}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700768
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700769void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800770 // Report the number of crashes for this OS version, but don't clear the
771 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -0700772 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800773 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700774 crashes_count,
775 1, // value of first bucket
776 500, // value of last bucket
777 100); // number of buckets
778
779
Ben Chanf05ab402014-08-07 00:54:59 -0700780 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700781 SendSample(version_cumulative_cpu_use_->Name(),
782 cpu_use_ms / 1000, // stat is in seconds
783 1, // device may be used very little...
784 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
785 100);
786
787 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
788 // can be zero. Avoid division by zero.
789 if (cpu_use_ms > 0) {
790 // Send the crash frequency since update in number of crashes per CPU year.
791 SendSample("Logging.KernelCrashesPerCpuYear",
792 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
793 1,
794 1000 * 1000, // about one crash every 30s of CPU time
795 100);
796 }
797
Ben Chanf05ab402014-08-07 00:54:59 -0700798 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700799 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700800 SendSample(version_cumulative_active_use_->Name(),
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700801 active_use_seconds,
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700802 1, // device may be used very little...
803 8 * 1000 * 1000, // ... or a lot (about 90 days)
804 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700805 // Same as above, but per year of active time.
806 SendSample("Logging.KernelCrashesPerActiveYear",
807 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
808 1,
809 1000 * 1000, // about one crash every 30s of active time
810 100);
811 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800812}
813
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700814void MetricsDaemon::SendAndResetDailyUseSample(
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700815 const scoped_ptr<PersistentInteger>& use) {
816 SendSample(use->Name(),
817 use->GetAndClear(),
818 1, // value of first bucket
819 kSecondsPerDay, // value of last bucket
820 50); // number of buckets
821}
822
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700823void MetricsDaemon::SendAndResetCrashIntervalSample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800824 const scoped_ptr<PersistentInteger>& interval) {
825 SendSample(interval->Name(),
826 interval->GetAndClear(),
827 1, // value of first bucket
828 4 * kSecondsPerWeek, // value of last bucket
829 50); // number of buckets
830}
831
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700832void MetricsDaemon::SendAndResetCrashFrequencySample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800833 const scoped_ptr<PersistentInteger>& frequency) {
834 SendSample(frequency->Name(),
835 frequency->GetAndClear(),
836 1, // value of first bucket
837 100, // value of last bucket
838 50); // number of buckets
839}
840
841void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700842 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700843 // TODO(semenzato): add a proper linear histogram to the Chrome external
844 // metrics API.
845 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
846 metrics_lib_->SendEnumToUMA(name, sample, max);
847}
Daniel Eratc83975a2014-04-04 08:53:44 -0700848
849void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
850 Time now_wall_time) {
851 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700852 daily_active_use_->Add(elapsed_seconds);
853 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -0700854 user_crash_interval_->Add(elapsed_seconds);
855 kernel_crash_interval_->Add(elapsed_seconds);
856 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
857 last_update_stats_time_ = now_ticks;
858
859 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
860 const int day = since_epoch.InDays();
861 const int week = day / 7;
862
863 if (daily_cycle_->Get() != day) {
864 daily_cycle_->Set(day);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700865 SendAndResetDailyUseSample(daily_active_use_);
866 SendAndResetCrashFrequencySample(any_crashes_daily_count_);
867 SendAndResetCrashFrequencySample(user_crashes_daily_count_);
868 SendAndResetCrashFrequencySample(kernel_crashes_daily_count_);
869 SendAndResetCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700870 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -0700871 }
872
873 if (weekly_cycle_->Get() != week) {
874 weekly_cycle_->Set(week);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700875 SendAndResetCrashFrequencySample(any_crashes_weekly_count_);
876 SendAndResetCrashFrequencySample(user_crashes_weekly_count_);
877 SendAndResetCrashFrequencySample(kernel_crashes_weekly_count_);
878 SendAndResetCrashFrequencySample(unclean_shutdowns_weekly_count_);
Daniel Eratc83975a2014-04-04 08:53:44 -0700879 }
880}
881
Steve Funge86591e2014-12-01 13:38:21 -0800882void MetricsDaemon::HandleUpdateStatsTimeout() {
883 UpdateStats(TimeTicks::Now(), Time::Now());
884 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
885 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
886 base::Unretained(this)),
887 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -0700888}