blob: acd96c07991a4f24515c74b9a662afb528403680 [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// For PRIu64 in inttypes.h, used by scanf. TODO(semenzato): replace
6// with libchromeos methods.
7#define __STDC_FORMAT_MACROS
8
9#include "metrics/metrics_daemon.h"
Darin Petkov65b01462010-04-14 13:32:20 -070010
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080011#include <fcntl.h>
Luigi Semenzato4a6c9422014-06-30 18:12:28 -070012#include <inttypes.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -070013#include <math.h>
Ken Mixter4c5daa42010-08-26 18:35:06 -070014#include <string.h>
Steve Funge86591e2014-12-01 13:38:21 -080015#include <sysexits.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -070016#include <time.h>
Darin Petkov65b01462010-04-14 13:32:20 -070017
Luigi Semenzato859b3f02014-02-05 15:33:19 -080018#include <base/files/file_path.h>
Ben Chan51bf92a2014-09-05 08:21:06 -070019#include <base/files/file_util.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080020#include <base/hash.h>
Darin Petkov65b01462010-04-14 13:32:20 -070021#include <base/logging.h>
Ben Chan2e6543d2014-02-05 23:26:25 -080022#include <base/strings/string_number_conversions.h>
23#include <base/strings/string_split.h>
24#include <base/strings/string_util.h>
25#include <base/strings/stringprintf.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080026#include <base/sys_info.h>
Darin Petkov40f25732013-04-29 15:07:31 +020027#include <chromeos/dbus/service_constants.h>
Steve Funge86591e2014-12-01 13:38:21 -080028#include <dbus/dbus.h>
29#include <dbus/message.h>
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -070030#include "uploader/upload_service.h"
Darin Petkov65b01462010-04-14 13:32:20 -070031
Ben Chan2e6543d2014-02-05 23:26:25 -080032using base::FilePath;
33using base::StringPrintf;
Darin Petkovf27f0362010-06-04 13:14:19 -070034using base::Time;
35using base::TimeDelta;
36using base::TimeTicks;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080037using chromeos_metrics::PersistentInteger;
Luigi Semenzato8accd332011-05-17 16:37:18 -070038using std::map;
Darin Petkov38d5cb02010-06-24 12:10:26 -070039using std::string;
Luigi Semenzato8accd332011-05-17 16:37:18 -070040using std::vector;
41
Daniel Eratc83975a2014-04-04 08:53:44 -070042namespace {
Darin Petkovf27f0362010-06-04 13:14:19 -070043
Darin Petkov703ec972010-04-27 11:02:18 -070044#define SAFE_MESSAGE(e) (e.message ? e.message : "unknown error")
Darin Petkov40f25732013-04-29 15:07:31 +020045
Daniel Eratc83975a2014-04-04 08:53:44 -070046const char kCrashReporterInterface[] = "org.chromium.CrashReporter";
47const char kCrashReporterUserCrashSignal[] = "UserCrash";
Steve Funge86591e2014-12-01 13:38:21 -080048const char kCrashReporterMatchRule[] =
49 "type='signal',interface='%s',path='/',member='%s'";
Darin Petkov41e06232010-05-03 16:45:37 -070050
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_),
190 server_));
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700191 upload_service_->Init(upload_interval_, metrics_file_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700192 upload_service_->UploadEvent();
193}
194
Ben Chanf05ab402014-08-07 00:54:59 -0700195uint32_t MetricsDaemon::GetOsVersionHash() {
196 static uint32_t cached_version_hash = 0;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800197 static bool version_hash_is_cached = false;
198 if (version_hash_is_cached)
199 return cached_version_hash;
200 version_hash_is_cached = true;
201 std::string version;
202 if (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_VERSION", &version)) {
203 cached_version_hash = base::Hash(version);
204 } else if (testing_) {
205 cached_version_hash = 42; // return any plausible value for the hash
206 } else {
207 LOG(FATAL) << "could not find CHROMEOS_RELEASE_VERSION";
208 }
209 return cached_version_hash;
210}
211
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700212void MetricsDaemon::Init(bool testing,
213 bool uploader_active,
214 MetricsLibraryInterface* metrics_lib,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700215 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700216 const string& vmstats_path,
217 const string& scaling_max_freq_path,
Steve Fung67906c62014-10-06 15:15:30 -0700218 const string& cpuinfo_max_freq_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700219 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700220 const string& server,
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700221 const string& metrics_file,
222 const string& config_root) {
Darin Petkov65b01462010-04-14 13:32:20 -0700223 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800224 uploader_active_ = uploader_active;
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700225 config_root_ = config_root;
Alex Vakulenko14595032014-08-28 14:59:56 -0700226 DCHECK(metrics_lib != nullptr);
Darin Petkovfc91b422010-05-12 13:05:45 -0700227 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700228
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700229 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700230 server_ = server;
231 metrics_file_ = metrics_file;
232
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700233 // Get ticks per second (HZ) on this system.
234 // Sysconf cannot fail, so no sanity checks are needed.
235 ticks_per_second_ = sysconf(_SC_CLK_TCK);
236
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700237 daily_active_use_.reset(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800238 new PersistentInteger("Logging.DailyUseTime"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700239 version_cumulative_active_use_.reset(
240 new PersistentInteger("Logging.CumulativeDailyUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700241 version_cumulative_cpu_use_.reset(
242 new PersistentInteger("Logging.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700243
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800244 kernel_crash_interval_.reset(
245 new PersistentInteger("Logging.KernelCrashInterval"));
246 unclean_shutdown_interval_.reset(
247 new PersistentInteger("Logging.UncleanShutdownInterval"));
248 user_crash_interval_.reset(
249 new PersistentInteger("Logging.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700250
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800251 any_crashes_daily_count_.reset(
252 new PersistentInteger("Logging.AnyCrashesDaily"));
253 any_crashes_weekly_count_.reset(
254 new PersistentInteger("Logging.AnyCrashesWeekly"));
255 user_crashes_daily_count_.reset(
256 new PersistentInteger("Logging.UserCrashesDaily"));
257 user_crashes_weekly_count_.reset(
258 new PersistentInteger("Logging.UserCrashesWeekly"));
259 kernel_crashes_daily_count_.reset(
260 new PersistentInteger("Logging.KernelCrashesDaily"));
261 kernel_crashes_weekly_count_.reset(
262 new PersistentInteger("Logging.KernelCrashesWeekly"));
263 kernel_crashes_version_count_.reset(
264 new PersistentInteger("Logging.KernelCrashesSinceUpdate"));
265 unclean_shutdowns_daily_count_.reset(
266 new PersistentInteger("Logging.UncleanShutdownsDaily"));
267 unclean_shutdowns_weekly_count_.reset(
268 new PersistentInteger("Logging.UncleanShutdownsWeekly"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700269
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800270 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
271 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
272 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800273
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700274 diskstats_path_ = diskstats_path;
275 vmstats_path_ = vmstats_path;
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700276 scaling_max_freq_path_ = scaling_max_freq_path;
277 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Steve Funge86591e2014-12-01 13:38:21 -0800278
279 // If testing, initialize Stats Reporter without connecting DBus
280 if (testing_)
281 StatsReporterInit();
282}
283
284int MetricsDaemon::OnInit() {
285 int return_code = chromeos::DBusDaemon::OnInit();
286 if (return_code != EX_OK)
287 return return_code;
288
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700289 StatsReporterInit();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800290
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700291 // Start collecting meminfo stats.
292 ScheduleMeminfoCallback(kMetricMeminfoInterval);
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800293 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
294 ScheduleMemuseCallback(kMemuseIntervals[0]);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700295
Steve Funge86591e2014-12-01 13:38:21 -0800296 if (testing_)
297 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700298
Steve Funge86591e2014-12-01 13:38:21 -0800299 bus_->AssertOnDBusThread();
300 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700301
Steve Funge86591e2014-12-01 13:38:21 -0800302 if (bus_->is_connected()) {
303 const std::string match_rule =
304 base::StringPrintf(kCrashReporterMatchRule,
305 kCrashReporterInterface,
306 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700307
Steve Funge86591e2014-12-01 13:38:21 -0800308 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700309
Steve Funge86591e2014-12-01 13:38:21 -0800310 DBusError error;
311 dbus_error_init(&error);
312 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700313
Steve Funge86591e2014-12-01 13:38:21 -0800314 if (dbus_error_is_set(&error)) {
315 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
316 << error.name << ": " << error.message;
317 return EX_SOFTWARE;
318 }
319 } else {
320 LOG(ERROR) << "DBus isn't connected.";
321 return EX_UNAVAILABLE;
Darin Petkov703ec972010-04-27 11:02:18 -0700322 }
323
Steve Funge86591e2014-12-01 13:38:21 -0800324 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
325 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
326 base::Unretained(this)),
327 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -0700328
Steve Funge86591e2014-12-01 13:38:21 -0800329 if (uploader_active_) {
Nathan Bullock0be0f732014-09-11 10:29:17 -0400330 LOG(INFO) << "uploader enabled";
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700331 upload_service_.reset(new UploadService(new SystemProfileCache(), server_));
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700332 upload_service_->Init(upload_interval_, metrics_file_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700333 }
Steve Funge86591e2014-12-01 13:38:21 -0800334
335 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700336}
337
Steve Funge86591e2014-12-01 13:38:21 -0800338void MetricsDaemon::OnShutdown(int* return_code) {
339 if (!testing_ && bus_->is_connected()) {
340 const std::string match_rule =
341 base::StringPrintf(kCrashReporterMatchRule,
342 kCrashReporterInterface,
343 kCrashReporterUserCrashSignal);
344
345 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
346
347 DBusError error;
348 dbus_error_init(&error);
349 bus_->RemoveMatch(match_rule, &error);
350
351 if (dbus_error_is_set(&error)) {
352 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
353 << error.name << ": " << error.message;
354 }
355 }
356 chromeos::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700357}
358
Darin Petkov703ec972010-04-27 11:02:18 -0700359// static
360DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
361 DBusMessage* message,
362 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700363 int message_type = dbus_message_get_type(message);
364 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700365 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700366 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
367 }
368
369 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700370 const std::string interface(dbus_message_get_interface(message));
371 const std::string member(dbus_message_get_member(message));
372 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700373
374 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
375
376 DBusMessageIter iter;
377 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700378 if (interface == kCrashReporterInterface) {
379 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700380 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700381 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700382 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700383 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
384 }
385
386 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700387}
388
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700389// One might argue that parts of this should go into
390// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
391
392TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700393 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
394 std::string proc_stat_string;
395 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
396 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
397 return TimeDelta();
398 }
399
400 std::vector<std::string> proc_stat_lines;
401 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
402 if (proc_stat_lines.empty()) {
403 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
404 << ": " << proc_stat_string;
405 return TimeDelta();
406 }
407 std::vector<std::string> proc_stat_totals;
408 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
409
Ben Chanf05ab402014-08-07 00:54:59 -0700410 uint64_t user_ticks, user_nice_ticks, system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700411 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
412 proc_stat_totals[0] != "cpu" ||
413 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
414 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
415 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
416 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
417 return TimeDelta(base::TimeDelta::FromSeconds(0));
418 }
419
Ben Chanf05ab402014-08-07 00:54:59 -0700420 uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700421
422 // Sanity check.
423 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
424 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
425 << " to " << total_cpu_use_ticks;
426 return TimeDelta();
427 }
428
Ben Chanf05ab402014-08-07 00:54:59 -0700429 uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700430 latest_cpu_use_ticks_ = total_cpu_use_ticks;
431 // Use microseconds to avoid significant truncations.
432 return base::TimeDelta::FromMicroseconds(
433 diff * 1000 * 1000 / ticks_per_second_);
434}
435
Darin Petkov1bb904e2010-06-16 15:58:06 -0700436void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700437 // Counts the active time up to now.
438 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700439
440 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800441 SendCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700442
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800443 any_crashes_daily_count_->Add(1);
444 any_crashes_weekly_count_->Add(1);
445 user_crashes_daily_count_->Add(1);
446 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700447}
448
Darin Petkov38d5cb02010-06-24 12:10:26 -0700449void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700450 // Counts the active time up to now.
451 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700452
453 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800454 SendCrashIntervalSample(kernel_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 kernel_crashes_daily_count_->Add(1);
459 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800460
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800461 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700462}
463
Ken Mixterccd84c02010-08-16 19:57:13 -0700464void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700465 // Counts the active time up to now.
466 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700467
468 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800469 SendCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700470
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800471 unclean_shutdowns_daily_count_->Add(1);
472 unclean_shutdowns_weekly_count_->Add(1);
473 any_crashes_daily_count_->Add(1);
474 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700475}
476
Luigi Semenzato8accd332011-05-17 16:37:18 -0700477bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700478 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800479 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700480 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700481
482 // Deletes the crash-detected file so that the daemon doesn't report
483 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800484 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700485 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700486}
487
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700488void MetricsDaemon::StatsReporterInit() {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800489 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700490 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800491 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700492 stats_state_ = kStatsLong;
493 stats_initial_time_ = GetActiveTime();
494 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700495 LOG(WARNING) << "not collecting disk stats";
496 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700497 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700498 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800499}
500
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700501void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800502 if (testing_) {
503 return;
504 }
Steve Funge86591e2014-12-01 13:38:21 -0800505 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
506 base::Bind(&MetricsDaemon::StatsCallback, base::Unretained(this)),
507 base::TimeDelta::FromSeconds(wait));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800508}
509
Ben Chanf05ab402014-08-07 00:54:59 -0700510bool MetricsDaemon::DiskStatsReadStats(uint64_t* read_sectors,
511 uint64_t* write_sectors) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800512 int nchars;
513 int nitems;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700514 bool success = false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800515 char line[200];
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700516 if (diskstats_path_.empty()) {
517 return false;
518 }
Luigi Semenzato0f132bb2011-02-28 11:17:43 -0800519 int file = HANDLE_EINTR(open(diskstats_path_.c_str(), O_RDONLY));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800520 if (file < 0) {
521 PLOG(WARNING) << "cannot open " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700522 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800523 }
524 nchars = HANDLE_EINTR(read(file, line, sizeof(line)));
525 if (nchars < 0) {
526 PLOG(WARNING) << "cannot read from " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700527 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800528 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700529 LOG_IF(WARNING, nchars == sizeof(line))
530 << "line too long in " << diskstats_path_;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800531 line[nchars] = '\0';
Nathan Bullockdc1ef3c2014-09-17 09:24:10 -0400532 nitems = sscanf(line, "%*d %*d %" PRIu64 " %*d %*d %*d %" PRIu64,
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800533 read_sectors, write_sectors);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700534 if (nitems == 2) {
535 success = true;
536 } else {
537 LOG(WARNING) << "found " << nitems << " items in "
538 << diskstats_path_ << ", expected 2";
539 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800540 }
Mike Frysinger3e8a8512014-05-14 16:14:37 -0400541 IGNORE_EINTR(close(file));
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700542 return success;
543}
544
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700545bool MetricsDaemon::VmStatsParseStats(const char* stats,
546 struct VmstatRecord* record) {
547 // a mapping of string name to field in VmstatRecord and whether we found it
548 struct mapping {
549 const string name;
550 uint64_t* value_p;
551 bool found;
552 } map[] =
553 { { .name = "pgmajfault",
554 .value_p = &record->page_faults_,
555 .found = false },
556 { .name = "pswpin",
557 .value_p = &record->swap_in_,
558 .found = false },
559 { .name = "pswpout",
560 .value_p = &record->swap_out_,
561 .found = false }, };
562
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700563 // Each line in the file has the form
564 // <ID> <VALUE>
565 // for instance:
566 // nr_free_pages 213427
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700567 vector<string> lines;
568 Tokenize(stats, "\n", &lines);
569 for (vector<string>::iterator it = lines.begin();
570 it != lines.end(); ++it) {
571 vector<string> tokens;
572 base::SplitString(*it, ' ', &tokens);
573 if (tokens.size() == 2) {
574 for (unsigned int i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
575 if (!tokens[0].compare(map[i].name)) {
576 if (!base::StringToUint64(tokens[1], map[i].value_p))
577 return false;
578 map[i].found = true;
579 }
580 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700581 } else {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700582 LOG(WARNING) << "unexpected vmstat format";
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700583 }
584 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700585 // make sure we got all the stats
586 for (unsigned i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
587 if (map[i].found == false) {
588 LOG(WARNING) << "vmstat missing " << map[i].name;
589 return false;
590 }
591 }
592 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700593}
594
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700595bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
596 string value_string;
597 FilePath* path = new FilePath(vmstats_path_);
Ben Chan2e6543d2014-02-05 23:26:25 -0800598 if (!base::ReadFileToString(*path, &value_string)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700599 delete path;
600 LOG(WARNING) << "cannot read " << vmstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700601 return false;
602 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700603 delete path;
604 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800605}
606
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700607bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700608 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700609 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800610 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700611 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
612 return false;
613 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800614 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700615 LOG(WARNING) << "no newline in " << value_string;
616 // Continue even though the lack of newline is suspicious.
617 }
618 if (!base::StringToInt(value_string, value)) {
619 LOG(WARNING) << "cannot convert " << value_string << " to int";
620 return false;
621 }
622 return true;
623}
624
625void MetricsDaemon::SendCpuThrottleMetrics() {
626 // |max_freq| is 0 only the first time through.
627 static int max_freq = 0;
628 if (max_freq == -1)
629 // Give up, as sysfs did not report max_freq correctly.
630 return;
631 if (max_freq == 0 || testing_) {
632 // One-time initialization of max_freq. (Every time when testing.)
633 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
634 max_freq = -1;
635 return;
636 }
637 if (max_freq == 0) {
638 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
639 max_freq = -1;
640 return;
641 }
642 if (max_freq % 10000 == 1000) {
643 // Special case: system has turbo mode, and max non-turbo frequency is
644 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
645 // being multiples of (at least) 10 MHz. Although there is no guarantee
646 // of this, it seems a fairly reasonable assumption. Otherwise we should
647 // read scaling_available_frequencies, sort the frequencies, compare the
648 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
649 // hack too, no telling when it will change).
650 max_freq -= 1000;
651 }
652 }
653 int scaled_freq = 0;
654 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
655 return;
656 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
657 // scaled_freq is not the actual turbo frequency. We indicate this situation
658 // with a 101% value.
659 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800660 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700661}
662
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700663// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700664
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700665void MetricsDaemon::StatsCallback() {
Ben Chanf05ab402014-08-07 00:54:59 -0700666 uint64_t read_sectors_now, write_sectors_now;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700667 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700668 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700669 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700670 if (testing_) {
671 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700672 delta_time = stats_state_ == kStatsShort ?
673 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700674 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700675 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
676 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700677 int delta_read = read_sectors_now - read_sectors_;
678 int delta_write = write_sectors_now - write_sectors_;
679 int read_sectors_per_second = delta_read / delta_time;
680 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700681 bool vmstats_success = VmStatsReadStats(&vmstats_now);
682 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
683 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
684 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
685 uint64_t page_faults_per_second = delta_faults / delta_time;
686 uint64_t swap_in_per_second = delta_swap_in / delta_time;
687 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800688
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700689 switch (stats_state_) {
690 case kStatsShort:
691 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800692 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700693 read_sectors_per_second,
694 1,
695 kMetricSectorsIOMax,
696 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800697 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700698 write_sectors_per_second,
699 1,
700 kMetricSectorsIOMax,
701 kMetricSectorsBuckets);
702 }
703 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800704 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700705 page_faults_per_second,
706 1,
707 kMetricPageFaultsMax,
708 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800709 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700710 swap_in_per_second,
711 1,
712 kMetricPageFaultsMax,
713 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800714 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700715 swap_out_per_second,
716 1,
717 kMetricPageFaultsMax,
718 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700719 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800720 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700721 stats_state_ = kStatsLong;
722 ScheduleStatsCallback(kMetricStatsLongInterval -
723 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800724 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700725 case kStatsLong:
726 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800727 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700728 read_sectors_per_second,
729 1,
730 kMetricSectorsIOMax,
731 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800732 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700733 write_sectors_per_second,
734 1,
735 kMetricSectorsIOMax,
736 kMetricSectorsBuckets);
737 // Reset sector counters.
738 read_sectors_ = read_sectors_now;
739 write_sectors_ = write_sectors_now;
740 }
741 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800742 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700743 page_faults_per_second,
744 1,
745 kMetricPageFaultsMax,
746 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800747 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700748 swap_in_per_second,
749 1,
750 kMetricPageFaultsMax,
751 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800752 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700753 swap_out_per_second,
754 1,
755 kMetricPageFaultsMax,
756 kMetricPageFaultsBuckets);
757
758 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700759 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700760 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700761 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700762 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800763 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700764 stats_state_ = kStatsShort;
765 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800766 break;
767 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700768 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800769 }
770}
771
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700772void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
773 if (testing_) {
774 return;
775 }
Steve Funge86591e2014-12-01 13:38:21 -0800776 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
777 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
778 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
779 base::TimeDelta::FromMilliseconds(kMetricMeminfoInterval)),
780 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700781}
782
Steve Funge86591e2014-12-01 13:38:21 -0800783void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700784 string meminfo_raw;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700785 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800786 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700787 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800788 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700789 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700790 // Make both calls even if the first one fails.
791 bool success = ProcessMeminfo(meminfo_raw);
Steve Funge86591e2014-12-01 13:38:21 -0800792 bool reschedule =
793 ReportZram(base::FilePath(FILE_PATH_LITERAL("/sys/block/zram0"))) &&
Luigi Semenzato96360192014-06-04 10:53:35 -0700794 success;
Steve Funge86591e2014-12-01 13:38:21 -0800795 if (reschedule) {
796 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
797 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
798 base::TimeDelta::FromMilliseconds(kMetricMeminfoInterval)),
799 wait);
800 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700801}
802
803// static
804bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700805 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700806 std::string content;
807 if (!base::ReadFileToString(path, &content)) {
808 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
809 return false;
810 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700811 // Remove final newline.
812 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700813 if (!base::StringToUint64(content, value)) {
814 LOG(WARNING) << "invalid integer: " << content;
815 return false;
816 }
817 return true;
818}
819
820bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
821 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700822 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700823 const size_t page_size = 4096;
824
825 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
826 &compr_data_size) ||
827 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
828 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
829 return false;
830 }
831
832 // |orig_data_size| does not include zero-filled pages.
833 orig_data_size += zero_pages * page_size;
834
835 const int compr_data_size_mb = compr_data_size >> 20;
836 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
837 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
838
839 // Report compressed size in megabytes. 100 MB or less has little impact.
840 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
841 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
842 // The compression ratio is multiplied by 100 for better resolution. The
843 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
844 // don't want samples when very little memory is being compressed.
845 if (compr_data_size_mb >= 1) {
846 SendSample("Platform.ZramCompressionRatioPercent",
847 orig_data_size * 100 / compr_data_size, 100, 600, 50);
848 }
849 // The values of interest for zero_pages are between 1MB and 1GB. The units
850 // are number of pages.
851 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
852 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
853
854 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700855}
856
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700857bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700858 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700859 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
860 { "MemFree", "MemFree" },
861 { "Buffers", "Buffers" },
862 { "Cached", "Cached" },
863 // { "SwapCached", "SwapCached" },
864 { "Active", "Active" },
865 { "Inactive", "Inactive" },
866 { "ActiveAnon", "Active(anon)" },
867 { "InactiveAnon", "Inactive(anon)" },
868 { "ActiveFile" , "Active(file)" },
869 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800870 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700871 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800872 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
873 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700874 // { "Dirty", "Dirty" },
875 // { "Writeback", "Writeback" },
876 { "AnonPages", "AnonPages" },
877 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800878 { "Shmem", "Shmem", kMeminfoOp_HistLog },
879 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700880 // { "SReclaimable", "SReclaimable" },
881 // { "SUnreclaim", "SUnreclaim" },
882 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700883 vector<MeminfoRecord> fields(fields_array,
884 fields_array + arraysize(fields_array));
885 if (!FillMeminfo(meminfo_raw, &fields)) {
886 return false;
887 }
888 int total_memory = fields[0].value;
889 if (total_memory == 0) {
890 // this "cannot happen"
891 LOG(WARNING) << "borked meminfo parser";
892 return false;
893 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800894 int swap_total = 0;
895 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700896 // Send all fields retrieved, except total memory.
897 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800898 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
899 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800900 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800901 switch (fields[i].op) {
902 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800903 // report value as percent of total memory
904 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800905 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800906 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800907 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800908 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800909 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800910 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800911 case kMeminfoOp_SwapTotal:
912 swap_total = fields[i].value;
913 case kMeminfoOp_SwapFree:
914 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800915 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700916 }
917 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800918 if (swap_total > 0) {
919 int swap_used = swap_total - swap_free;
920 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800921 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
922 SendLinearSample("Platform.MeminfoSwapUsedPercent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800923 100, 101);
924 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700925 return true;
926}
927
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700928bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
929 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700930 vector<string> lines;
931 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700932
933 // Scan meminfo output and collect field values. Each field name has to
934 // match a meminfo entry (case insensitive) after removing non-alpha
935 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700936 unsigned int ifield = 0;
937 for (unsigned int iline = 0;
938 iline < nlines && ifield < fields->size();
939 iline++) {
940 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700941 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700942 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
943 // Name matches. Parse value and save.
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700944 char* rest;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700945 (*fields)[ifield].value =
946 static_cast<int>(strtol(tokens[1].c_str(), &rest, 10));
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700947 if (*rest != '\0') {
948 LOG(WARNING) << "missing meminfo value";
949 return false;
950 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700951 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700952 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700953 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700954 if (ifield < fields->size()) {
955 // End of input reached while scanning.
956 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
957 << " and following";
958 return false;
959 }
960 return true;
961}
962
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800963void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700964 if (testing_) {
965 return;
966 }
Steve Funge86591e2014-12-01 13:38:21 -0800967 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
968 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
969 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700970}
971
972void MetricsDaemon::MemuseCallback() {
973 // Since we only care about active time (i.e. uptime minus sleep time) but
974 // the callbacks are driven by real time (uptime), we check if we should
975 // reschedule this callback due to intervening sleep periods.
976 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800977 // Avoid intervals of less than one second.
978 double remaining_time = ceil(memuse_final_time_ - now);
979 if (remaining_time > 0) {
980 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700981 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800982 // Report stats and advance the measurement interval unless there are
983 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700984 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800985 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
986 double interval = kMemuseIntervals[memuse_interval_index_++];
987 memuse_final_time_ = now + interval;
988 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700989 }
990 }
991}
992
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700993bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700994 string meminfo_raw;
995 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800996 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700997 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
998 return false;
999 }
1000 return ProcessMemuse(meminfo_raw);
1001}
1002
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001003bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001004 static const MeminfoRecord fields_array[] = {
1005 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
1006 { "ActiveAnon", "Active(anon)" },
1007 { "InactiveAnon", "Inactive(anon)" },
1008 };
1009 vector<MeminfoRecord> fields(fields_array,
1010 fields_array + arraysize(fields_array));
1011 if (!FillMeminfo(meminfo_raw, &fields)) {
1012 return false;
1013 }
1014 int total = fields[0].value;
1015 int active_anon = fields[1].value;
1016 int inactive_anon = fields[2].value;
1017 if (total == 0) {
1018 // this "cannot happen"
1019 LOG(WARNING) << "borked meminfo parser";
1020 return false;
1021 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -08001022 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
1023 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001024 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -07001025 100, 101);
1026 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001027}
1028
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001029void MetricsDaemon::ReportDailyUse(int use_seconds) {
1030 if (use_seconds <= 0)
Darin Petkov1bb904e2010-06-16 15:58:06 -07001031 return;
1032
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001033 int minutes = (use_seconds + kSecondsPerMinute / 2) / kSecondsPerMinute;
1034 SendSample("Logging.DailyUseTime",
1035 minutes,
1036 1,
1037 kMinutesPerDay * 30 * 2, // cumulative---two months worth
1038 50);
Darin Petkovf1e85e42010-06-10 15:59:53 -07001039}
1040
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001041void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -07001042 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -07001043 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -07001044}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001045
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001046void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001047 // Report the number of crashes for this OS version, but don't clear the
1048 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -07001049 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001050 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001051 crashes_count,
1052 1, // value of first bucket
1053 500, // value of last bucket
1054 100); // number of buckets
1055
1056
Ben Chanf05ab402014-08-07 00:54:59 -07001057 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001058 SendSample(version_cumulative_cpu_use_->Name(),
1059 cpu_use_ms / 1000, // stat is in seconds
1060 1, // device may be used very little...
1061 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
1062 100);
1063
1064 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
1065 // can be zero. Avoid division by zero.
1066 if (cpu_use_ms > 0) {
1067 // Send the crash frequency since update in number of crashes per CPU year.
1068 SendSample("Logging.KernelCrashesPerCpuYear",
1069 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
1070 1,
1071 1000 * 1000, // about one crash every 30s of CPU time
1072 100);
1073 }
1074
Ben Chanf05ab402014-08-07 00:54:59 -07001075 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001076 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001077 SendSample(version_cumulative_active_use_->Name(),
1078 active_use_seconds / 1000, // stat is in seconds
1079 1, // device may be used very little...
1080 8 * 1000 * 1000, // ... or a lot (about 90 days)
1081 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001082 // Same as above, but per year of active time.
1083 SendSample("Logging.KernelCrashesPerActiveYear",
1084 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
1085 1,
1086 1000 * 1000, // about one crash every 30s of active time
1087 100);
1088 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001089}
1090
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001091void MetricsDaemon::SendDailyUseSample(
1092 const scoped_ptr<PersistentInteger>& use) {
1093 SendSample(use->Name(),
1094 use->GetAndClear(),
1095 1, // value of first bucket
1096 kSecondsPerDay, // value of last bucket
1097 50); // number of buckets
1098}
1099
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001100void MetricsDaemon::SendCrashIntervalSample(
1101 const scoped_ptr<PersistentInteger>& interval) {
1102 SendSample(interval->Name(),
1103 interval->GetAndClear(),
1104 1, // value of first bucket
1105 4 * kSecondsPerWeek, // value of last bucket
1106 50); // number of buckets
1107}
1108
1109void MetricsDaemon::SendCrashFrequencySample(
1110 const scoped_ptr<PersistentInteger>& frequency) {
1111 SendSample(frequency->Name(),
1112 frequency->GetAndClear(),
1113 1, // value of first bucket
1114 100, // value of last bucket
1115 50); // number of buckets
1116}
1117
1118void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001119 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001120 // TODO(semenzato): add a proper linear histogram to the Chrome external
1121 // metrics API.
1122 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1123 metrics_lib_->SendEnumToUMA(name, sample, max);
1124}
Daniel Eratc83975a2014-04-04 08:53:44 -07001125
1126void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
1127 Time now_wall_time) {
1128 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001129 daily_active_use_->Add(elapsed_seconds);
1130 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -07001131 user_crash_interval_->Add(elapsed_seconds);
1132 kernel_crash_interval_->Add(elapsed_seconds);
1133 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
1134 last_update_stats_time_ = now_ticks;
1135
1136 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
1137 const int day = since_epoch.InDays();
1138 const int week = day / 7;
1139
1140 if (daily_cycle_->Get() != day) {
1141 daily_cycle_->Set(day);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001142 SendDailyUseSample(daily_active_use_);
1143 SendDailyUseSample(version_cumulative_active_use_);
Daniel Eratc83975a2014-04-04 08:53:44 -07001144 SendCrashFrequencySample(any_crashes_daily_count_);
1145 SendCrashFrequencySample(user_crashes_daily_count_);
1146 SendCrashFrequencySample(kernel_crashes_daily_count_);
1147 SendCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001148 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -07001149 }
1150
1151 if (weekly_cycle_->Get() != week) {
1152 weekly_cycle_->Set(week);
1153 SendCrashFrequencySample(any_crashes_weekly_count_);
1154 SendCrashFrequencySample(user_crashes_weekly_count_);
1155 SendCrashFrequencySample(kernel_crashes_weekly_count_);
1156 SendCrashFrequencySample(unclean_shutdowns_weekly_count_);
1157 }
1158}
1159
Steve Funge86591e2014-12-01 13:38:21 -08001160void MetricsDaemon::HandleUpdateStatsTimeout() {
1161 UpdateStats(TimeTicks::Now(), Time::Now());
1162 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
1163 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
1164 base::Unretained(this)),
1165 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -07001166}