blob: 9568592d57b45e42f8183dabd757233e72a6e8d1 [file] [log] [blame]
Darin Petkov8032dd02011-05-09 16:33:19 -07001// Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
Darin Petkov65b01462010-04-14 13:32:20 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Luigi Semenzato4a6c9422014-06-30 18:12:28 -07005#include "metrics/metrics_daemon.h"
Darin Petkov65b01462010-04-14 13:32:20 -07006
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -08007#include <fcntl.h>
Luigi Semenzato4a6c9422014-06-30 18:12:28 -07008#include <inttypes.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -07009#include <math.h>
Ken Mixter4c5daa42010-08-26 18:35:06 -070010#include <string.h>
Steve Funge86591e2014-12-01 13:38:21 -080011#include <sysexits.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -070012#include <time.h>
Darin Petkov65b01462010-04-14 13:32:20 -070013
Luigi Semenzato859b3f02014-02-05 15:33:19 -080014#include <base/files/file_path.h>
Ben Chan51bf92a2014-09-05 08:21:06 -070015#include <base/files/file_util.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080016#include <base/hash.h>
Darin Petkov65b01462010-04-14 13:32:20 -070017#include <base/logging.h>
Ben Chan2e6543d2014-02-05 23:26:25 -080018#include <base/strings/string_number_conversions.h>
19#include <base/strings/string_split.h>
20#include <base/strings/string_util.h>
21#include <base/strings/stringprintf.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080022#include <base/sys_info.h>
Darin Petkov40f25732013-04-29 15:07:31 +020023#include <chromeos/dbus/service_constants.h>
Steve Funge86591e2014-12-01 13:38:21 -080024#include <dbus/dbus.h>
25#include <dbus/message.h>
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -070026#include "uploader/upload_service.h"
Darin Petkov65b01462010-04-14 13:32:20 -070027
Ben Chan2e6543d2014-02-05 23:26:25 -080028using base::FilePath;
29using base::StringPrintf;
Darin Petkovf27f0362010-06-04 13:14:19 -070030using base::Time;
31using base::TimeDelta;
32using base::TimeTicks;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080033using chromeos_metrics::PersistentInteger;
Luigi Semenzato8accd332011-05-17 16:37:18 -070034using std::map;
Darin Petkov38d5cb02010-06-24 12:10:26 -070035using std::string;
Luigi Semenzato8accd332011-05-17 16:37:18 -070036using std::vector;
37
Daniel Eratc83975a2014-04-04 08:53:44 -070038namespace {
Darin Petkovf27f0362010-06-04 13:14:19 -070039
Darin Petkov703ec972010-04-27 11:02:18 -070040#define SAFE_MESSAGE(e) (e.message ? e.message : "unknown error")
Darin Petkov40f25732013-04-29 15:07:31 +020041
Daniel Eratc83975a2014-04-04 08:53:44 -070042const char kCrashReporterInterface[] = "org.chromium.CrashReporter";
43const char kCrashReporterUserCrashSignal[] = "UserCrash";
Steve Funge86591e2014-12-01 13:38:21 -080044const char kCrashReporterMatchRule[] =
45 "type='signal',interface='%s',path='/',member='%s'";
Darin Petkov41e06232010-05-03 16:45:37 -070046
Ben Chan067ec8b2015-02-17 13:54:04 -080047// Build type of an official build.
48// See src/third_party/chromiumos-overlay/chromeos/scripts/cros_set_lsb_release.
49const char kOfficialBuild[] = "Official Build";
50
Daniel Eratc83975a2014-04-04 08:53:44 -070051const int kSecondsPerMinute = 60;
52const int kMinutesPerHour = 60;
53const int kHoursPerDay = 24;
54const int kMinutesPerDay = kHoursPerDay * kMinutesPerHour;
55const int kSecondsPerDay = kSecondsPerMinute * kMinutesPerDay;
56const int kDaysPerWeek = 7;
57const int kSecondsPerWeek = kSecondsPerDay * kDaysPerWeek;
Darin Petkov41e06232010-05-03 16:45:37 -070058
Daniel Eratc83975a2014-04-04 08:53:44 -070059// Interval between calls to UpdateStats().
Steve Funge86591e2014-12-01 13:38:21 -080060const uint32_t kUpdateStatsIntervalMs = 300000;
Darin Petkov65b01462010-04-14 13:32:20 -070061
Luigi Semenzatoc5a92342014-02-14 15:05:51 -080062const char kKernelCrashDetectedFile[] = "/var/run/kernel-crash-detected";
Daniel Eratc83975a2014-04-04 08:53:44 -070063const char kUncleanShutdownDetectedFile[] =
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080064 "/var/run/unclean-shutdown-detected";
Ken Mixterccd84c02010-08-16 19:57:13 -070065
Daniel Eratc83975a2014-04-04 08:53:44 -070066} // namespace
67
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080068// disk stats metrics
69
70// The {Read,Write}Sectors numbers are in sectors/second.
71// A sector is usually 512 bytes.
72
73const char MetricsDaemon::kMetricReadSectorsLongName[] =
74 "Platform.ReadSectorsLong";
75const char MetricsDaemon::kMetricWriteSectorsLongName[] =
76 "Platform.WriteSectorsLong";
77const char MetricsDaemon::kMetricReadSectorsShortName[] =
78 "Platform.ReadSectorsShort";
79const char MetricsDaemon::kMetricWriteSectorsShortName[] =
80 "Platform.WriteSectorsShort";
81
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070082const int MetricsDaemon::kMetricStatsShortInterval = 1; // seconds
83const int MetricsDaemon::kMetricStatsLongInterval = 30; // seconds
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080084
Luigi Semenzato29c7ef92011-04-12 14:12:35 -070085const int MetricsDaemon::kMetricMeminfoInterval = 30; // seconds
86
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080087// Assume a max rate of 250Mb/s for reads (worse for writes) and 512 byte
88// sectors.
89const int MetricsDaemon::kMetricSectorsIOMax = 500000; // sectors/second
90const int MetricsDaemon::kMetricSectorsBuckets = 50; // buckets
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070091// Page size is 4k, sector size is 0.5k. We're not interested in page fault
92// rates that the disk cannot sustain.
93const int MetricsDaemon::kMetricPageFaultsMax = kMetricSectorsIOMax / 8;
94const int MetricsDaemon::kMetricPageFaultsBuckets = 50;
95
96// Major page faults, i.e. the ones that require data to be read from disk.
97
98const char MetricsDaemon::kMetricPageFaultsLongName[] =
99 "Platform.PageFaultsLong";
100const char MetricsDaemon::kMetricPageFaultsShortName[] =
101 "Platform.PageFaultsShort";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800102
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700103// Swap in and Swap out
104
105const char MetricsDaemon::kMetricSwapInLongName[] =
106 "Platform.SwapInLong";
107const char MetricsDaemon::kMetricSwapInShortName[] =
108 "Platform.SwapInShort";
109
110const char MetricsDaemon::kMetricSwapOutLongName[] =
111 "Platform.SwapOutLong";
112const char MetricsDaemon::kMetricSwapOutShortName[] =
113 "Platform.SwapOutShort";
114
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700115const char MetricsDaemon::kMetricsProcStatFileName[] = "/proc/stat";
116const int MetricsDaemon::kMetricsProcStatFirstLineItemsCount = 11;
117
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700118// Thermal CPU throttling.
119
120const char MetricsDaemon::kMetricScaledCpuFrequencyName[] =
121 "Platform.CpuFrequencyThermalScaling";
122
Luigi Semenzato96360192014-06-04 10:53:35 -0700123// Zram sysfs entries.
124
125const char MetricsDaemon::kComprDataSizeName[] = "compr_data_size";
126const char MetricsDaemon::kOrigDataSizeName[] = "orig_data_size";
127const char MetricsDaemon::kZeroPagesName[] = "zero_pages";
128
Luigi Semenzato8accd332011-05-17 16:37:18 -0700129// Memory use stats collection intervals. We collect some memory use interval
130// at these intervals after boot, and we stop collecting after the last one,
131// with the assumption that in most cases the memory use won't change much
132// after that.
133static const int kMemuseIntervals[] = {
134 1 * kSecondsPerMinute, // 1 minute mark
135 4 * kSecondsPerMinute, // 5 minute mark
136 25 * kSecondsPerMinute, // 0.5 hour mark
137 120 * kSecondsPerMinute, // 2.5 hour mark
138 600 * kSecondsPerMinute, // 12.5 hour mark
139};
140
Darin Petkovf1e85e42010-06-10 15:59:53 -0700141MetricsDaemon::MetricsDaemon()
Steve Funge86591e2014-12-01 13:38:21 -0800142 : memuse_final_time_(0),
Luigi Semenzato8accd332011-05-17 16:37:18 -0700143 memuse_interval_index_(0),
144 read_sectors_(0),
145 write_sectors_(0),
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700146 vmstats_(),
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700147 stats_state_(kStatsShort),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700148 stats_initial_time_(0),
149 ticks_per_second_(0),
150 latest_cpu_use_ticks_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700151
Ken Mixter4c5daa42010-08-26 18:35:06 -0700152MetricsDaemon::~MetricsDaemon() {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700153}
154
Luigi Semenzato8accd332011-05-17 16:37:18 -0700155double MetricsDaemon::GetActiveTime() {
156 struct timespec ts;
157 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
158 if (r < 0) {
159 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
160 return 0;
161 } else {
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700162 return ts.tv_sec + static_cast<double>(ts.tv_nsec) / (1000 * 1000 * 1000);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700163 }
164}
165
Steve Funge86591e2014-12-01 13:38:21 -0800166int MetricsDaemon::Run() {
Ken Mixterccd84c02010-08-16 19:57:13 -0700167 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
168 ProcessKernelCrash();
169 }
170
171 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
172 ProcessUncleanShutdown();
173 }
174
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800175 // On OS version change, clear version stats (which are reported daily).
Ben Chanf05ab402014-08-07 00:54:59 -0700176 int32_t version = GetOsVersionHash();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800177 if (version_cycle_->Get() != version) {
178 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800179 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700180 version_cumulative_active_use_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700181 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800182 }
183
Steve Funge86591e2014-12-01 13:38:21 -0800184 return chromeos::DBusDaemon::Run();
Darin Petkov65b01462010-04-14 13:32:20 -0700185}
186
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700187void MetricsDaemon::RunUploaderTest() {
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700188 upload_service_.reset(new UploadService(new SystemProfileCache(true,
189 config_root_),
Bertrand SIMONNETe4fa61e2015-02-18 09:38:55 -0800190 metrics_lib_,
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700191 server_));
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700192 upload_service_->Init(upload_interval_, metrics_file_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700193 upload_service_->UploadEvent();
194}
195
Ben Chanf05ab402014-08-07 00:54:59 -0700196uint32_t MetricsDaemon::GetOsVersionHash() {
197 static uint32_t cached_version_hash = 0;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800198 static bool version_hash_is_cached = false;
199 if (version_hash_is_cached)
200 return cached_version_hash;
201 version_hash_is_cached = true;
202 std::string version;
203 if (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_VERSION", &version)) {
204 cached_version_hash = base::Hash(version);
205 } else if (testing_) {
206 cached_version_hash = 42; // return any plausible value for the hash
207 } else {
208 LOG(FATAL) << "could not find CHROMEOS_RELEASE_VERSION";
209 }
210 return cached_version_hash;
211}
212
Ben Chan067ec8b2015-02-17 13:54:04 -0800213bool MetricsDaemon::IsOnOfficialBuild() const {
214 std::string build_type;
215 return (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_BUILD_TYPE",
216 &build_type) &&
217 build_type == kOfficialBuild);
218}
219
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700220void MetricsDaemon::Init(bool testing,
221 bool uploader_active,
222 MetricsLibraryInterface* metrics_lib,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700223 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700224 const string& vmstats_path,
225 const string& scaling_max_freq_path,
Steve Fung67906c62014-10-06 15:15:30 -0700226 const string& cpuinfo_max_freq_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700227 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700228 const string& server,
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700229 const string& metrics_file,
230 const string& config_root) {
Darin Petkov65b01462010-04-14 13:32:20 -0700231 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800232 uploader_active_ = uploader_active;
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700233 config_root_ = config_root;
Alex Vakulenko14595032014-08-28 14:59:56 -0700234 DCHECK(metrics_lib != nullptr);
Darin Petkovfc91b422010-05-12 13:05:45 -0700235 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700236
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700237 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700238 server_ = server;
239 metrics_file_ = metrics_file;
240
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700241 // Get ticks per second (HZ) on this system.
242 // Sysconf cannot fail, so no sanity checks are needed.
243 ticks_per_second_ = sysconf(_SC_CLK_TCK);
244
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700245 daily_active_use_.reset(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800246 new PersistentInteger("Logging.DailyUseTime"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700247 version_cumulative_active_use_.reset(
248 new PersistentInteger("Logging.CumulativeDailyUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700249 version_cumulative_cpu_use_.reset(
250 new PersistentInteger("Logging.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700251
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800252 kernel_crash_interval_.reset(
253 new PersistentInteger("Logging.KernelCrashInterval"));
254 unclean_shutdown_interval_.reset(
255 new PersistentInteger("Logging.UncleanShutdownInterval"));
256 user_crash_interval_.reset(
257 new PersistentInteger("Logging.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700258
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800259 any_crashes_daily_count_.reset(
260 new PersistentInteger("Logging.AnyCrashesDaily"));
261 any_crashes_weekly_count_.reset(
262 new PersistentInteger("Logging.AnyCrashesWeekly"));
263 user_crashes_daily_count_.reset(
264 new PersistentInteger("Logging.UserCrashesDaily"));
265 user_crashes_weekly_count_.reset(
266 new PersistentInteger("Logging.UserCrashesWeekly"));
267 kernel_crashes_daily_count_.reset(
268 new PersistentInteger("Logging.KernelCrashesDaily"));
269 kernel_crashes_weekly_count_.reset(
270 new PersistentInteger("Logging.KernelCrashesWeekly"));
271 kernel_crashes_version_count_.reset(
272 new PersistentInteger("Logging.KernelCrashesSinceUpdate"));
273 unclean_shutdowns_daily_count_.reset(
274 new PersistentInteger("Logging.UncleanShutdownsDaily"));
275 unclean_shutdowns_weekly_count_.reset(
276 new PersistentInteger("Logging.UncleanShutdownsWeekly"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700277
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800278 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
279 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
280 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800281
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700282 diskstats_path_ = diskstats_path;
283 vmstats_path_ = vmstats_path;
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700284 scaling_max_freq_path_ = scaling_max_freq_path;
285 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Steve Funge86591e2014-12-01 13:38:21 -0800286
287 // If testing, initialize Stats Reporter without connecting DBus
288 if (testing_)
289 StatsReporterInit();
290}
291
292int MetricsDaemon::OnInit() {
293 int return_code = chromeos::DBusDaemon::OnInit();
294 if (return_code != EX_OK)
295 return return_code;
296
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700297 StatsReporterInit();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800298
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700299 // Start collecting meminfo stats.
300 ScheduleMeminfoCallback(kMetricMeminfoInterval);
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800301 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
302 ScheduleMemuseCallback(kMemuseIntervals[0]);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700303
Steve Funge86591e2014-12-01 13:38:21 -0800304 if (testing_)
305 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700306
Steve Funge86591e2014-12-01 13:38:21 -0800307 bus_->AssertOnDBusThread();
308 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700309
Steve Funge86591e2014-12-01 13:38:21 -0800310 if (bus_->is_connected()) {
311 const std::string match_rule =
312 base::StringPrintf(kCrashReporterMatchRule,
313 kCrashReporterInterface,
314 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700315
Steve Funge86591e2014-12-01 13:38:21 -0800316 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700317
Steve Funge86591e2014-12-01 13:38:21 -0800318 DBusError error;
319 dbus_error_init(&error);
320 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700321
Steve Funge86591e2014-12-01 13:38:21 -0800322 if (dbus_error_is_set(&error)) {
323 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
324 << error.name << ": " << error.message;
325 return EX_SOFTWARE;
326 }
327 } else {
328 LOG(ERROR) << "DBus isn't connected.";
329 return EX_UNAVAILABLE;
Darin Petkov703ec972010-04-27 11:02:18 -0700330 }
331
Steve Funge86591e2014-12-01 13:38:21 -0800332 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
333 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
334 base::Unretained(this)),
335 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -0700336
Steve Funge86591e2014-12-01 13:38:21 -0800337 if (uploader_active_) {
Ben Chan067ec8b2015-02-17 13:54:04 -0800338 if (IsOnOfficialBuild()) {
339 LOG(INFO) << "uploader enabled";
340 upload_service_.reset(
Bertrand SIMONNETe4fa61e2015-02-18 09:38:55 -0800341 new UploadService(new SystemProfileCache(), metrics_lib_, server_));
Ben Chan067ec8b2015-02-17 13:54:04 -0800342 upload_service_->Init(upload_interval_, metrics_file_);
343 } else {
344 LOG(INFO) << "uploader disabled on non-official build";
345 }
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700346 }
Steve Funge86591e2014-12-01 13:38:21 -0800347
348 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700349}
350
Steve Funge86591e2014-12-01 13:38:21 -0800351void MetricsDaemon::OnShutdown(int* return_code) {
352 if (!testing_ && bus_->is_connected()) {
353 const std::string match_rule =
354 base::StringPrintf(kCrashReporterMatchRule,
355 kCrashReporterInterface,
356 kCrashReporterUserCrashSignal);
357
358 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
359
360 DBusError error;
361 dbus_error_init(&error);
362 bus_->RemoveMatch(match_rule, &error);
363
364 if (dbus_error_is_set(&error)) {
365 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
366 << error.name << ": " << error.message;
367 }
368 }
369 chromeos::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700370}
371
Darin Petkov703ec972010-04-27 11:02:18 -0700372// static
373DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
374 DBusMessage* message,
375 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700376 int message_type = dbus_message_get_type(message);
377 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700378 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700379 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
380 }
381
382 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700383 const std::string interface(dbus_message_get_interface(message));
384 const std::string member(dbus_message_get_member(message));
385 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700386
387 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
388
389 DBusMessageIter iter;
390 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700391 if (interface == kCrashReporterInterface) {
392 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700393 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700394 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700395 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700396 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
397 }
398
399 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700400}
401
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700402// One might argue that parts of this should go into
403// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
404
405TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700406 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
407 std::string proc_stat_string;
408 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
409 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
410 return TimeDelta();
411 }
412
413 std::vector<std::string> proc_stat_lines;
414 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
415 if (proc_stat_lines.empty()) {
416 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
417 << ": " << proc_stat_string;
418 return TimeDelta();
419 }
420 std::vector<std::string> proc_stat_totals;
421 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
422
Ben Chanf05ab402014-08-07 00:54:59 -0700423 uint64_t user_ticks, user_nice_ticks, system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700424 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
425 proc_stat_totals[0] != "cpu" ||
426 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
427 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
428 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
429 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
430 return TimeDelta(base::TimeDelta::FromSeconds(0));
431 }
432
Ben Chanf05ab402014-08-07 00:54:59 -0700433 uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700434
435 // Sanity check.
436 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
437 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
438 << " to " << total_cpu_use_ticks;
439 return TimeDelta();
440 }
441
Ben Chanf05ab402014-08-07 00:54:59 -0700442 uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700443 latest_cpu_use_ticks_ = total_cpu_use_ticks;
444 // Use microseconds to avoid significant truncations.
445 return base::TimeDelta::FromMicroseconds(
446 diff * 1000 * 1000 / ticks_per_second_);
447}
448
Darin Petkov1bb904e2010-06-16 15:58:06 -0700449void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700450 // Counts the active time up to now.
451 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700452
453 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800454 SendCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700455
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800456 any_crashes_daily_count_->Add(1);
457 any_crashes_weekly_count_->Add(1);
458 user_crashes_daily_count_->Add(1);
459 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700460}
461
Darin Petkov38d5cb02010-06-24 12:10:26 -0700462void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700463 // Counts the active time up to now.
464 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700465
466 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800467 SendCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700468
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800469 any_crashes_daily_count_->Add(1);
470 any_crashes_weekly_count_->Add(1);
471 kernel_crashes_daily_count_->Add(1);
472 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800473
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800474 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700475}
476
Ken Mixterccd84c02010-08-16 19:57:13 -0700477void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700478 // Counts the active time up to now.
479 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700480
481 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800482 SendCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700483
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800484 unclean_shutdowns_daily_count_->Add(1);
485 unclean_shutdowns_weekly_count_->Add(1);
486 any_crashes_daily_count_->Add(1);
487 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700488}
489
Luigi Semenzato8accd332011-05-17 16:37:18 -0700490bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700491 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800492 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700493 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700494
495 // Deletes the crash-detected file so that the daemon doesn't report
496 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800497 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700498 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700499}
500
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700501void MetricsDaemon::StatsReporterInit() {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800502 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700503 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800504 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700505 stats_state_ = kStatsLong;
506 stats_initial_time_ = GetActiveTime();
507 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700508 LOG(WARNING) << "not collecting disk stats";
509 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700510 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700511 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800512}
513
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700514void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800515 if (testing_) {
516 return;
517 }
Steve Funge86591e2014-12-01 13:38:21 -0800518 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
519 base::Bind(&MetricsDaemon::StatsCallback, base::Unretained(this)),
520 base::TimeDelta::FromSeconds(wait));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800521}
522
Ben Chanf05ab402014-08-07 00:54:59 -0700523bool MetricsDaemon::DiskStatsReadStats(uint64_t* read_sectors,
524 uint64_t* write_sectors) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800525 int nchars;
526 int nitems;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700527 bool success = false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800528 char line[200];
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700529 if (diskstats_path_.empty()) {
530 return false;
531 }
Luigi Semenzato0f132bb2011-02-28 11:17:43 -0800532 int file = HANDLE_EINTR(open(diskstats_path_.c_str(), O_RDONLY));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800533 if (file < 0) {
534 PLOG(WARNING) << "cannot open " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700535 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800536 }
537 nchars = HANDLE_EINTR(read(file, line, sizeof(line)));
538 if (nchars < 0) {
539 PLOG(WARNING) << "cannot read from " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700540 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800541 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700542 LOG_IF(WARNING, nchars == sizeof(line))
543 << "line too long in " << diskstats_path_;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800544 line[nchars] = '\0';
Nathan Bullockdc1ef3c2014-09-17 09:24:10 -0400545 nitems = sscanf(line, "%*d %*d %" PRIu64 " %*d %*d %*d %" PRIu64,
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800546 read_sectors, write_sectors);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700547 if (nitems == 2) {
548 success = true;
549 } else {
550 LOG(WARNING) << "found " << nitems << " items in "
551 << diskstats_path_ << ", expected 2";
552 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800553 }
Mike Frysinger3e8a8512014-05-14 16:14:37 -0400554 IGNORE_EINTR(close(file));
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700555 return success;
556}
557
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700558bool MetricsDaemon::VmStatsParseStats(const char* stats,
559 struct VmstatRecord* record) {
560 // a mapping of string name to field in VmstatRecord and whether we found it
561 struct mapping {
562 const string name;
563 uint64_t* value_p;
564 bool found;
565 } map[] =
566 { { .name = "pgmajfault",
567 .value_p = &record->page_faults_,
568 .found = false },
569 { .name = "pswpin",
570 .value_p = &record->swap_in_,
571 .found = false },
572 { .name = "pswpout",
573 .value_p = &record->swap_out_,
574 .found = false }, };
575
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700576 // Each line in the file has the form
577 // <ID> <VALUE>
578 // for instance:
579 // nr_free_pages 213427
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700580 vector<string> lines;
581 Tokenize(stats, "\n", &lines);
582 for (vector<string>::iterator it = lines.begin();
583 it != lines.end(); ++it) {
584 vector<string> tokens;
585 base::SplitString(*it, ' ', &tokens);
586 if (tokens.size() == 2) {
587 for (unsigned int i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
588 if (!tokens[0].compare(map[i].name)) {
589 if (!base::StringToUint64(tokens[1], map[i].value_p))
590 return false;
591 map[i].found = true;
592 }
593 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700594 } else {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700595 LOG(WARNING) << "unexpected vmstat format";
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700596 }
597 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700598 // make sure we got all the stats
599 for (unsigned i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
600 if (map[i].found == false) {
601 LOG(WARNING) << "vmstat missing " << map[i].name;
602 return false;
603 }
604 }
605 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700606}
607
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700608bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
609 string value_string;
610 FilePath* path = new FilePath(vmstats_path_);
Ben Chan2e6543d2014-02-05 23:26:25 -0800611 if (!base::ReadFileToString(*path, &value_string)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700612 delete path;
613 LOG(WARNING) << "cannot read " << vmstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700614 return false;
615 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700616 delete path;
617 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800618}
619
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700620bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700621 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700622 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800623 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700624 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
625 return false;
626 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800627 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700628 LOG(WARNING) << "no newline in " << value_string;
629 // Continue even though the lack of newline is suspicious.
630 }
631 if (!base::StringToInt(value_string, value)) {
632 LOG(WARNING) << "cannot convert " << value_string << " to int";
633 return false;
634 }
635 return true;
636}
637
638void MetricsDaemon::SendCpuThrottleMetrics() {
639 // |max_freq| is 0 only the first time through.
640 static int max_freq = 0;
641 if (max_freq == -1)
642 // Give up, as sysfs did not report max_freq correctly.
643 return;
644 if (max_freq == 0 || testing_) {
645 // One-time initialization of max_freq. (Every time when testing.)
646 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
647 max_freq = -1;
648 return;
649 }
650 if (max_freq == 0) {
651 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
652 max_freq = -1;
653 return;
654 }
655 if (max_freq % 10000 == 1000) {
656 // Special case: system has turbo mode, and max non-turbo frequency is
657 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
658 // being multiples of (at least) 10 MHz. Although there is no guarantee
659 // of this, it seems a fairly reasonable assumption. Otherwise we should
660 // read scaling_available_frequencies, sort the frequencies, compare the
661 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
662 // hack too, no telling when it will change).
663 max_freq -= 1000;
664 }
665 }
666 int scaled_freq = 0;
667 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
668 return;
669 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
670 // scaled_freq is not the actual turbo frequency. We indicate this situation
671 // with a 101% value.
672 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800673 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700674}
675
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700676// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700677
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700678void MetricsDaemon::StatsCallback() {
Ben Chanf05ab402014-08-07 00:54:59 -0700679 uint64_t read_sectors_now, write_sectors_now;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700680 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700681 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700682 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700683 if (testing_) {
684 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700685 delta_time = stats_state_ == kStatsShort ?
686 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700687 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700688 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
689 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700690 int delta_read = read_sectors_now - read_sectors_;
691 int delta_write = write_sectors_now - write_sectors_;
692 int read_sectors_per_second = delta_read / delta_time;
693 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700694 bool vmstats_success = VmStatsReadStats(&vmstats_now);
695 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
696 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
697 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
698 uint64_t page_faults_per_second = delta_faults / delta_time;
699 uint64_t swap_in_per_second = delta_swap_in / delta_time;
700 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800701
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700702 switch (stats_state_) {
703 case kStatsShort:
704 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800705 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700706 read_sectors_per_second,
707 1,
708 kMetricSectorsIOMax,
709 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800710 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700711 write_sectors_per_second,
712 1,
713 kMetricSectorsIOMax,
714 kMetricSectorsBuckets);
715 }
716 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800717 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700718 page_faults_per_second,
719 1,
720 kMetricPageFaultsMax,
721 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800722 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700723 swap_in_per_second,
724 1,
725 kMetricPageFaultsMax,
726 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800727 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700728 swap_out_per_second,
729 1,
730 kMetricPageFaultsMax,
731 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700732 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800733 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700734 stats_state_ = kStatsLong;
735 ScheduleStatsCallback(kMetricStatsLongInterval -
736 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800737 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700738 case kStatsLong:
739 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800740 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700741 read_sectors_per_second,
742 1,
743 kMetricSectorsIOMax,
744 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800745 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700746 write_sectors_per_second,
747 1,
748 kMetricSectorsIOMax,
749 kMetricSectorsBuckets);
750 // Reset sector counters.
751 read_sectors_ = read_sectors_now;
752 write_sectors_ = write_sectors_now;
753 }
754 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800755 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700756 page_faults_per_second,
757 1,
758 kMetricPageFaultsMax,
759 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800760 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700761 swap_in_per_second,
762 1,
763 kMetricPageFaultsMax,
764 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800765 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700766 swap_out_per_second,
767 1,
768 kMetricPageFaultsMax,
769 kMetricPageFaultsBuckets);
770
771 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700772 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700773 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700774 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700775 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800776 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700777 stats_state_ = kStatsShort;
778 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800779 break;
780 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700781 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800782 }
783}
784
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700785void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
786 if (testing_) {
787 return;
788 }
Steve Funge86591e2014-12-01 13:38:21 -0800789 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
790 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
791 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800792 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800793 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700794}
795
Steve Funge86591e2014-12-01 13:38:21 -0800796void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700797 string meminfo_raw;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700798 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800799 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700800 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800801 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700802 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700803 // Make both calls even if the first one fails.
804 bool success = ProcessMeminfo(meminfo_raw);
Steve Funge86591e2014-12-01 13:38:21 -0800805 bool reschedule =
806 ReportZram(base::FilePath(FILE_PATH_LITERAL("/sys/block/zram0"))) &&
Luigi Semenzato96360192014-06-04 10:53:35 -0700807 success;
Steve Funge86591e2014-12-01 13:38:21 -0800808 if (reschedule) {
809 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
810 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800811 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800812 wait);
813 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700814}
815
816// static
817bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700818 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700819 std::string content;
820 if (!base::ReadFileToString(path, &content)) {
821 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
822 return false;
823 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700824 // Remove final newline.
825 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700826 if (!base::StringToUint64(content, value)) {
827 LOG(WARNING) << "invalid integer: " << content;
828 return false;
829 }
830 return true;
831}
832
833bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
834 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700835 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700836 const size_t page_size = 4096;
837
838 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
839 &compr_data_size) ||
840 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
841 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
842 return false;
843 }
844
845 // |orig_data_size| does not include zero-filled pages.
846 orig_data_size += zero_pages * page_size;
847
848 const int compr_data_size_mb = compr_data_size >> 20;
849 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
850 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
851
852 // Report compressed size in megabytes. 100 MB or less has little impact.
853 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
854 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
855 // The compression ratio is multiplied by 100 for better resolution. The
856 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
857 // don't want samples when very little memory is being compressed.
858 if (compr_data_size_mb >= 1) {
859 SendSample("Platform.ZramCompressionRatioPercent",
860 orig_data_size * 100 / compr_data_size, 100, 600, 50);
861 }
862 // The values of interest for zero_pages are between 1MB and 1GB. The units
863 // are number of pages.
864 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
865 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
866
867 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700868}
869
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700870bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700871 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700872 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
873 { "MemFree", "MemFree" },
874 { "Buffers", "Buffers" },
875 { "Cached", "Cached" },
876 // { "SwapCached", "SwapCached" },
877 { "Active", "Active" },
878 { "Inactive", "Inactive" },
879 { "ActiveAnon", "Active(anon)" },
880 { "InactiveAnon", "Inactive(anon)" },
881 { "ActiveFile" , "Active(file)" },
882 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800883 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700884 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800885 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
886 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700887 // { "Dirty", "Dirty" },
888 // { "Writeback", "Writeback" },
889 { "AnonPages", "AnonPages" },
890 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800891 { "Shmem", "Shmem", kMeminfoOp_HistLog },
892 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700893 // { "SReclaimable", "SReclaimable" },
894 // { "SUnreclaim", "SUnreclaim" },
895 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700896 vector<MeminfoRecord> fields(fields_array,
897 fields_array + arraysize(fields_array));
898 if (!FillMeminfo(meminfo_raw, &fields)) {
899 return false;
900 }
901 int total_memory = fields[0].value;
902 if (total_memory == 0) {
903 // this "cannot happen"
904 LOG(WARNING) << "borked meminfo parser";
905 return false;
906 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800907 int swap_total = 0;
908 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700909 // Send all fields retrieved, except total memory.
910 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800911 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
912 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800913 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800914 switch (fields[i].op) {
915 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800916 // report value as percent of total memory
917 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800918 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800919 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800920 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800921 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800922 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800923 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800924 case kMeminfoOp_SwapTotal:
925 swap_total = fields[i].value;
926 case kMeminfoOp_SwapFree:
927 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800928 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700929 }
930 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800931 if (swap_total > 0) {
932 int swap_used = swap_total - swap_free;
933 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800934 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
935 SendLinearSample("Platform.MeminfoSwapUsedPercent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800936 100, 101);
937 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700938 return true;
939}
940
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700941bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
942 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700943 vector<string> lines;
944 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700945
946 // Scan meminfo output and collect field values. Each field name has to
947 // match a meminfo entry (case insensitive) after removing non-alpha
948 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700949 unsigned int ifield = 0;
950 for (unsigned int iline = 0;
951 iline < nlines && ifield < fields->size();
952 iline++) {
953 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700954 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700955 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
956 // Name matches. Parse value and save.
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700957 char* rest;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700958 (*fields)[ifield].value =
959 static_cast<int>(strtol(tokens[1].c_str(), &rest, 10));
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700960 if (*rest != '\0') {
961 LOG(WARNING) << "missing meminfo value";
962 return false;
963 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700964 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700965 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700966 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700967 if (ifield < fields->size()) {
968 // End of input reached while scanning.
969 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
970 << " and following";
971 return false;
972 }
973 return true;
974}
975
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800976void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700977 if (testing_) {
978 return;
979 }
Steve Funge86591e2014-12-01 13:38:21 -0800980 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
981 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
982 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700983}
984
985void MetricsDaemon::MemuseCallback() {
986 // Since we only care about active time (i.e. uptime minus sleep time) but
987 // the callbacks are driven by real time (uptime), we check if we should
988 // reschedule this callback due to intervening sleep periods.
989 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800990 // Avoid intervals of less than one second.
991 double remaining_time = ceil(memuse_final_time_ - now);
992 if (remaining_time > 0) {
993 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700994 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800995 // Report stats and advance the measurement interval unless there are
996 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700997 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800998 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
999 double interval = kMemuseIntervals[memuse_interval_index_++];
1000 memuse_final_time_ = now + interval;
1001 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001002 }
1003 }
1004}
1005
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001006bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001007 string meminfo_raw;
1008 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -08001009 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001010 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
1011 return false;
1012 }
1013 return ProcessMemuse(meminfo_raw);
1014}
1015
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001016bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001017 static const MeminfoRecord fields_array[] = {
1018 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
1019 { "ActiveAnon", "Active(anon)" },
1020 { "InactiveAnon", "Inactive(anon)" },
1021 };
1022 vector<MeminfoRecord> fields(fields_array,
1023 fields_array + arraysize(fields_array));
1024 if (!FillMeminfo(meminfo_raw, &fields)) {
1025 return false;
1026 }
1027 int total = fields[0].value;
1028 int active_anon = fields[1].value;
1029 int inactive_anon = fields[2].value;
1030 if (total == 0) {
1031 // this "cannot happen"
1032 LOG(WARNING) << "borked meminfo parser";
1033 return false;
1034 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -08001035 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
1036 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001037 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -07001038 100, 101);
1039 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001040}
1041
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001042void MetricsDaemon::ReportDailyUse(int use_seconds) {
1043 if (use_seconds <= 0)
Darin Petkov1bb904e2010-06-16 15:58:06 -07001044 return;
1045
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001046 int minutes = (use_seconds + kSecondsPerMinute / 2) / kSecondsPerMinute;
1047 SendSample("Logging.DailyUseTime",
1048 minutes,
1049 1,
1050 kMinutesPerDay * 30 * 2, // cumulative---two months worth
1051 50);
Darin Petkovf1e85e42010-06-10 15:59:53 -07001052}
1053
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001054void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -07001055 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -07001056 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -07001057}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001058
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001059void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001060 // Report the number of crashes for this OS version, but don't clear the
1061 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -07001062 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001063 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001064 crashes_count,
1065 1, // value of first bucket
1066 500, // value of last bucket
1067 100); // number of buckets
1068
1069
Ben Chanf05ab402014-08-07 00:54:59 -07001070 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001071 SendSample(version_cumulative_cpu_use_->Name(),
1072 cpu_use_ms / 1000, // stat is in seconds
1073 1, // device may be used very little...
1074 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
1075 100);
1076
1077 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
1078 // can be zero. Avoid division by zero.
1079 if (cpu_use_ms > 0) {
1080 // Send the crash frequency since update in number of crashes per CPU year.
1081 SendSample("Logging.KernelCrashesPerCpuYear",
1082 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
1083 1,
1084 1000 * 1000, // about one crash every 30s of CPU time
1085 100);
1086 }
1087
Ben Chanf05ab402014-08-07 00:54:59 -07001088 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001089 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001090 SendSample(version_cumulative_active_use_->Name(),
1091 active_use_seconds / 1000, // stat is in seconds
1092 1, // device may be used very little...
1093 8 * 1000 * 1000, // ... or a lot (about 90 days)
1094 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001095 // Same as above, but per year of active time.
1096 SendSample("Logging.KernelCrashesPerActiveYear",
1097 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
1098 1,
1099 1000 * 1000, // about one crash every 30s of active time
1100 100);
1101 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001102}
1103
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001104void MetricsDaemon::SendDailyUseSample(
1105 const scoped_ptr<PersistentInteger>& use) {
1106 SendSample(use->Name(),
1107 use->GetAndClear(),
1108 1, // value of first bucket
1109 kSecondsPerDay, // value of last bucket
1110 50); // number of buckets
1111}
1112
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001113void MetricsDaemon::SendCrashIntervalSample(
1114 const scoped_ptr<PersistentInteger>& interval) {
1115 SendSample(interval->Name(),
1116 interval->GetAndClear(),
1117 1, // value of first bucket
1118 4 * kSecondsPerWeek, // value of last bucket
1119 50); // number of buckets
1120}
1121
1122void MetricsDaemon::SendCrashFrequencySample(
1123 const scoped_ptr<PersistentInteger>& frequency) {
1124 SendSample(frequency->Name(),
1125 frequency->GetAndClear(),
1126 1, // value of first bucket
1127 100, // value of last bucket
1128 50); // number of buckets
1129}
1130
1131void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001132 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001133 // TODO(semenzato): add a proper linear histogram to the Chrome external
1134 // metrics API.
1135 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1136 metrics_lib_->SendEnumToUMA(name, sample, max);
1137}
Daniel Eratc83975a2014-04-04 08:53:44 -07001138
1139void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
1140 Time now_wall_time) {
1141 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001142 daily_active_use_->Add(elapsed_seconds);
1143 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -07001144 user_crash_interval_->Add(elapsed_seconds);
1145 kernel_crash_interval_->Add(elapsed_seconds);
1146 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
1147 last_update_stats_time_ = now_ticks;
1148
1149 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
1150 const int day = since_epoch.InDays();
1151 const int week = day / 7;
1152
1153 if (daily_cycle_->Get() != day) {
1154 daily_cycle_->Set(day);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001155 SendDailyUseSample(daily_active_use_);
1156 SendDailyUseSample(version_cumulative_active_use_);
Daniel Eratc83975a2014-04-04 08:53:44 -07001157 SendCrashFrequencySample(any_crashes_daily_count_);
1158 SendCrashFrequencySample(user_crashes_daily_count_);
1159 SendCrashFrequencySample(kernel_crashes_daily_count_);
1160 SendCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001161 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -07001162 }
1163
1164 if (weekly_cycle_->Get() != week) {
1165 weekly_cycle_->Set(week);
1166 SendCrashFrequencySample(any_crashes_weekly_count_);
1167 SendCrashFrequencySample(user_crashes_weekly_count_);
1168 SendCrashFrequencySample(kernel_crashes_weekly_count_);
1169 SendCrashFrequencySample(unclean_shutdowns_weekly_count_);
1170 }
1171}
1172
Steve Funge86591e2014-12-01 13:38:21 -08001173void MetricsDaemon::HandleUpdateStatsTimeout() {
1174 UpdateStats(TimeTicks::Now(), Time::Now());
1175 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
1176 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
1177 base::Unretained(this)),
1178 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -07001179}