blob: 4a69d8b4cf3cacdf38b2a4f2f0156ef1768fbe19 [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
Ben Chan067ec8b2015-02-17 13:54:04 -080051// Build type of an official build.
52// See src/third_party/chromiumos-overlay/chromeos/scripts/cros_set_lsb_release.
53const char kOfficialBuild[] = "Official Build";
54
Daniel Eratc83975a2014-04-04 08:53:44 -070055const int kSecondsPerMinute = 60;
56const int kMinutesPerHour = 60;
57const int kHoursPerDay = 24;
58const int kMinutesPerDay = kHoursPerDay * kMinutesPerHour;
59const int kSecondsPerDay = kSecondsPerMinute * kMinutesPerDay;
60const int kDaysPerWeek = 7;
61const int kSecondsPerWeek = kSecondsPerDay * kDaysPerWeek;
Darin Petkov41e06232010-05-03 16:45:37 -070062
Daniel Eratc83975a2014-04-04 08:53:44 -070063// Interval between calls to UpdateStats().
Steve Funge86591e2014-12-01 13:38:21 -080064const uint32_t kUpdateStatsIntervalMs = 300000;
Darin Petkov65b01462010-04-14 13:32:20 -070065
Luigi Semenzatoc5a92342014-02-14 15:05:51 -080066const char kKernelCrashDetectedFile[] = "/var/run/kernel-crash-detected";
Daniel Eratc83975a2014-04-04 08:53:44 -070067const char kUncleanShutdownDetectedFile[] =
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080068 "/var/run/unclean-shutdown-detected";
Ken Mixterccd84c02010-08-16 19:57:13 -070069
Daniel Eratc83975a2014-04-04 08:53:44 -070070} // namespace
71
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080072// disk stats metrics
73
74// The {Read,Write}Sectors numbers are in sectors/second.
75// A sector is usually 512 bytes.
76
77const char MetricsDaemon::kMetricReadSectorsLongName[] =
78 "Platform.ReadSectorsLong";
79const char MetricsDaemon::kMetricWriteSectorsLongName[] =
80 "Platform.WriteSectorsLong";
81const char MetricsDaemon::kMetricReadSectorsShortName[] =
82 "Platform.ReadSectorsShort";
83const char MetricsDaemon::kMetricWriteSectorsShortName[] =
84 "Platform.WriteSectorsShort";
85
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070086const int MetricsDaemon::kMetricStatsShortInterval = 1; // seconds
87const int MetricsDaemon::kMetricStatsLongInterval = 30; // seconds
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080088
Luigi Semenzato29c7ef92011-04-12 14:12:35 -070089const int MetricsDaemon::kMetricMeminfoInterval = 30; // seconds
90
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080091// Assume a max rate of 250Mb/s for reads (worse for writes) and 512 byte
92// sectors.
93const int MetricsDaemon::kMetricSectorsIOMax = 500000; // sectors/second
94const int MetricsDaemon::kMetricSectorsBuckets = 50; // buckets
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070095// Page size is 4k, sector size is 0.5k. We're not interested in page fault
96// rates that the disk cannot sustain.
97const int MetricsDaemon::kMetricPageFaultsMax = kMetricSectorsIOMax / 8;
98const int MetricsDaemon::kMetricPageFaultsBuckets = 50;
99
100// Major page faults, i.e. the ones that require data to be read from disk.
101
102const char MetricsDaemon::kMetricPageFaultsLongName[] =
103 "Platform.PageFaultsLong";
104const char MetricsDaemon::kMetricPageFaultsShortName[] =
105 "Platform.PageFaultsShort";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800106
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700107// Swap in and Swap out
108
109const char MetricsDaemon::kMetricSwapInLongName[] =
110 "Platform.SwapInLong";
111const char MetricsDaemon::kMetricSwapInShortName[] =
112 "Platform.SwapInShort";
113
114const char MetricsDaemon::kMetricSwapOutLongName[] =
115 "Platform.SwapOutLong";
116const char MetricsDaemon::kMetricSwapOutShortName[] =
117 "Platform.SwapOutShort";
118
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700119const char MetricsDaemon::kMetricsProcStatFileName[] = "/proc/stat";
120const int MetricsDaemon::kMetricsProcStatFirstLineItemsCount = 11;
121
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700122// Thermal CPU throttling.
123
124const char MetricsDaemon::kMetricScaledCpuFrequencyName[] =
125 "Platform.CpuFrequencyThermalScaling";
126
Luigi Semenzato96360192014-06-04 10:53:35 -0700127// Zram sysfs entries.
128
129const char MetricsDaemon::kComprDataSizeName[] = "compr_data_size";
130const char MetricsDaemon::kOrigDataSizeName[] = "orig_data_size";
131const char MetricsDaemon::kZeroPagesName[] = "zero_pages";
132
Luigi Semenzato8accd332011-05-17 16:37:18 -0700133// Memory use stats collection intervals. We collect some memory use interval
134// at these intervals after boot, and we stop collecting after the last one,
135// with the assumption that in most cases the memory use won't change much
136// after that.
137static const int kMemuseIntervals[] = {
138 1 * kSecondsPerMinute, // 1 minute mark
139 4 * kSecondsPerMinute, // 5 minute mark
140 25 * kSecondsPerMinute, // 0.5 hour mark
141 120 * kSecondsPerMinute, // 2.5 hour mark
142 600 * kSecondsPerMinute, // 12.5 hour mark
143};
144
Darin Petkovf1e85e42010-06-10 15:59:53 -0700145MetricsDaemon::MetricsDaemon()
Steve Funge86591e2014-12-01 13:38:21 -0800146 : memuse_final_time_(0),
Luigi Semenzato8accd332011-05-17 16:37:18 -0700147 memuse_interval_index_(0),
148 read_sectors_(0),
149 write_sectors_(0),
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700150 vmstats_(),
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700151 stats_state_(kStatsShort),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700152 stats_initial_time_(0),
153 ticks_per_second_(0),
154 latest_cpu_use_ticks_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700155
Ken Mixter4c5daa42010-08-26 18:35:06 -0700156MetricsDaemon::~MetricsDaemon() {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700157}
158
Luigi Semenzato8accd332011-05-17 16:37:18 -0700159double MetricsDaemon::GetActiveTime() {
160 struct timespec ts;
161 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
162 if (r < 0) {
163 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
164 return 0;
165 } else {
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700166 return ts.tv_sec + static_cast<double>(ts.tv_nsec) / (1000 * 1000 * 1000);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700167 }
168}
169
Steve Funge86591e2014-12-01 13:38:21 -0800170int MetricsDaemon::Run() {
Ken Mixterccd84c02010-08-16 19:57:13 -0700171 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
172 ProcessKernelCrash();
173 }
174
175 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
176 ProcessUncleanShutdown();
177 }
178
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800179 // On OS version change, clear version stats (which are reported daily).
Ben Chanf05ab402014-08-07 00:54:59 -0700180 int32_t version = GetOsVersionHash();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800181 if (version_cycle_->Get() != version) {
182 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800183 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700184 version_cumulative_active_use_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700185 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800186 }
187
Steve Funge86591e2014-12-01 13:38:21 -0800188 return chromeos::DBusDaemon::Run();
Darin Petkov65b01462010-04-14 13:32:20 -0700189}
190
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700191void MetricsDaemon::RunUploaderTest() {
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700192 upload_service_.reset(new UploadService(new SystemProfileCache(true,
193 config_root_),
194 server_));
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700195 upload_service_->Init(upload_interval_, metrics_file_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700196 upload_service_->UploadEvent();
197}
198
Ben Chanf05ab402014-08-07 00:54:59 -0700199uint32_t MetricsDaemon::GetOsVersionHash() {
200 static uint32_t cached_version_hash = 0;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800201 static bool version_hash_is_cached = false;
202 if (version_hash_is_cached)
203 return cached_version_hash;
204 version_hash_is_cached = true;
205 std::string version;
206 if (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_VERSION", &version)) {
207 cached_version_hash = base::Hash(version);
208 } else if (testing_) {
209 cached_version_hash = 42; // return any plausible value for the hash
210 } else {
211 LOG(FATAL) << "could not find CHROMEOS_RELEASE_VERSION";
212 }
213 return cached_version_hash;
214}
215
Ben Chan067ec8b2015-02-17 13:54:04 -0800216bool MetricsDaemon::IsOnOfficialBuild() const {
217 std::string build_type;
218 return (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_BUILD_TYPE",
219 &build_type) &&
220 build_type == kOfficialBuild);
221}
222
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700223void MetricsDaemon::Init(bool testing,
224 bool uploader_active,
225 MetricsLibraryInterface* metrics_lib,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700226 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700227 const string& vmstats_path,
228 const string& scaling_max_freq_path,
Steve Fung67906c62014-10-06 15:15:30 -0700229 const string& cpuinfo_max_freq_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700230 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700231 const string& server,
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700232 const string& metrics_file,
233 const string& config_root) {
Darin Petkov65b01462010-04-14 13:32:20 -0700234 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800235 uploader_active_ = uploader_active;
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700236 config_root_ = config_root;
Alex Vakulenko14595032014-08-28 14:59:56 -0700237 DCHECK(metrics_lib != nullptr);
Darin Petkovfc91b422010-05-12 13:05:45 -0700238 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700239
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700240 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700241 server_ = server;
242 metrics_file_ = metrics_file;
243
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700244 // Get ticks per second (HZ) on this system.
245 // Sysconf cannot fail, so no sanity checks are needed.
246 ticks_per_second_ = sysconf(_SC_CLK_TCK);
247
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700248 daily_active_use_.reset(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800249 new PersistentInteger("Logging.DailyUseTime"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700250 version_cumulative_active_use_.reset(
251 new PersistentInteger("Logging.CumulativeDailyUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700252 version_cumulative_cpu_use_.reset(
253 new PersistentInteger("Logging.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700254
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800255 kernel_crash_interval_.reset(
256 new PersistentInteger("Logging.KernelCrashInterval"));
257 unclean_shutdown_interval_.reset(
258 new PersistentInteger("Logging.UncleanShutdownInterval"));
259 user_crash_interval_.reset(
260 new PersistentInteger("Logging.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700261
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800262 any_crashes_daily_count_.reset(
263 new PersistentInteger("Logging.AnyCrashesDaily"));
264 any_crashes_weekly_count_.reset(
265 new PersistentInteger("Logging.AnyCrashesWeekly"));
266 user_crashes_daily_count_.reset(
267 new PersistentInteger("Logging.UserCrashesDaily"));
268 user_crashes_weekly_count_.reset(
269 new PersistentInteger("Logging.UserCrashesWeekly"));
270 kernel_crashes_daily_count_.reset(
271 new PersistentInteger("Logging.KernelCrashesDaily"));
272 kernel_crashes_weekly_count_.reset(
273 new PersistentInteger("Logging.KernelCrashesWeekly"));
274 kernel_crashes_version_count_.reset(
275 new PersistentInteger("Logging.KernelCrashesSinceUpdate"));
276 unclean_shutdowns_daily_count_.reset(
277 new PersistentInteger("Logging.UncleanShutdownsDaily"));
278 unclean_shutdowns_weekly_count_.reset(
279 new PersistentInteger("Logging.UncleanShutdownsWeekly"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700280
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800281 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
282 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
283 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800284
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700285 diskstats_path_ = diskstats_path;
286 vmstats_path_ = vmstats_path;
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700287 scaling_max_freq_path_ = scaling_max_freq_path;
288 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Steve Funge86591e2014-12-01 13:38:21 -0800289
290 // If testing, initialize Stats Reporter without connecting DBus
291 if (testing_)
292 StatsReporterInit();
293}
294
295int MetricsDaemon::OnInit() {
296 int return_code = chromeos::DBusDaemon::OnInit();
297 if (return_code != EX_OK)
298 return return_code;
299
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700300 StatsReporterInit();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800301
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700302 // Start collecting meminfo stats.
303 ScheduleMeminfoCallback(kMetricMeminfoInterval);
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800304 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
305 ScheduleMemuseCallback(kMemuseIntervals[0]);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700306
Steve Funge86591e2014-12-01 13:38:21 -0800307 if (testing_)
308 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700309
Steve Funge86591e2014-12-01 13:38:21 -0800310 bus_->AssertOnDBusThread();
311 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700312
Steve Funge86591e2014-12-01 13:38:21 -0800313 if (bus_->is_connected()) {
314 const std::string match_rule =
315 base::StringPrintf(kCrashReporterMatchRule,
316 kCrashReporterInterface,
317 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700318
Steve Funge86591e2014-12-01 13:38:21 -0800319 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700320
Steve Funge86591e2014-12-01 13:38:21 -0800321 DBusError error;
322 dbus_error_init(&error);
323 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700324
Steve Funge86591e2014-12-01 13:38:21 -0800325 if (dbus_error_is_set(&error)) {
326 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
327 << error.name << ": " << error.message;
328 return EX_SOFTWARE;
329 }
330 } else {
331 LOG(ERROR) << "DBus isn't connected.";
332 return EX_UNAVAILABLE;
Darin Petkov703ec972010-04-27 11:02:18 -0700333 }
334
Steve Funge86591e2014-12-01 13:38:21 -0800335 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
336 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
337 base::Unretained(this)),
338 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -0700339
Steve Funge86591e2014-12-01 13:38:21 -0800340 if (uploader_active_) {
Ben Chan067ec8b2015-02-17 13:54:04 -0800341 if (IsOnOfficialBuild()) {
342 LOG(INFO) << "uploader enabled";
343 upload_service_.reset(
344 new UploadService(new SystemProfileCache(), server_));
345 upload_service_->Init(upload_interval_, metrics_file_);
346 } else {
347 LOG(INFO) << "uploader disabled on non-official build";
348 }
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700349 }
Steve Funge86591e2014-12-01 13:38:21 -0800350
351 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700352}
353
Steve Funge86591e2014-12-01 13:38:21 -0800354void MetricsDaemon::OnShutdown(int* return_code) {
355 if (!testing_ && bus_->is_connected()) {
356 const std::string match_rule =
357 base::StringPrintf(kCrashReporterMatchRule,
358 kCrashReporterInterface,
359 kCrashReporterUserCrashSignal);
360
361 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
362
363 DBusError error;
364 dbus_error_init(&error);
365 bus_->RemoveMatch(match_rule, &error);
366
367 if (dbus_error_is_set(&error)) {
368 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
369 << error.name << ": " << error.message;
370 }
371 }
372 chromeos::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700373}
374
Darin Petkov703ec972010-04-27 11:02:18 -0700375// static
376DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
377 DBusMessage* message,
378 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700379 int message_type = dbus_message_get_type(message);
380 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700381 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700382 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
383 }
384
385 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700386 const std::string interface(dbus_message_get_interface(message));
387 const std::string member(dbus_message_get_member(message));
388 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700389
390 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
391
392 DBusMessageIter iter;
393 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700394 if (interface == kCrashReporterInterface) {
395 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700396 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700397 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700398 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700399 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
400 }
401
402 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700403}
404
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700405// One might argue that parts of this should go into
406// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
407
408TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700409 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
410 std::string proc_stat_string;
411 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
412 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
413 return TimeDelta();
414 }
415
416 std::vector<std::string> proc_stat_lines;
417 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
418 if (proc_stat_lines.empty()) {
419 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
420 << ": " << proc_stat_string;
421 return TimeDelta();
422 }
423 std::vector<std::string> proc_stat_totals;
424 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
425
Ben Chanf05ab402014-08-07 00:54:59 -0700426 uint64_t user_ticks, user_nice_ticks, system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700427 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
428 proc_stat_totals[0] != "cpu" ||
429 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
430 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
431 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
432 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
433 return TimeDelta(base::TimeDelta::FromSeconds(0));
434 }
435
Ben Chanf05ab402014-08-07 00:54:59 -0700436 uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700437
438 // Sanity check.
439 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
440 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
441 << " to " << total_cpu_use_ticks;
442 return TimeDelta();
443 }
444
Ben Chanf05ab402014-08-07 00:54:59 -0700445 uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700446 latest_cpu_use_ticks_ = total_cpu_use_ticks;
447 // Use microseconds to avoid significant truncations.
448 return base::TimeDelta::FromMicroseconds(
449 diff * 1000 * 1000 / ticks_per_second_);
450}
451
Darin Petkov1bb904e2010-06-16 15:58:06 -0700452void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700453 // Counts the active time up to now.
454 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700455
456 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800457 SendCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700458
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800459 any_crashes_daily_count_->Add(1);
460 any_crashes_weekly_count_->Add(1);
461 user_crashes_daily_count_->Add(1);
462 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700463}
464
Darin Petkov38d5cb02010-06-24 12:10:26 -0700465void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700466 // Counts the active time up to now.
467 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700468
469 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800470 SendCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700471
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800472 any_crashes_daily_count_->Add(1);
473 any_crashes_weekly_count_->Add(1);
474 kernel_crashes_daily_count_->Add(1);
475 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800476
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800477 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700478}
479
Ken Mixterccd84c02010-08-16 19:57:13 -0700480void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700481 // Counts the active time up to now.
482 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700483
484 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800485 SendCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700486
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800487 unclean_shutdowns_daily_count_->Add(1);
488 unclean_shutdowns_weekly_count_->Add(1);
489 any_crashes_daily_count_->Add(1);
490 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700491}
492
Luigi Semenzato8accd332011-05-17 16:37:18 -0700493bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700494 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800495 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700496 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700497
498 // Deletes the crash-detected file so that the daemon doesn't report
499 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800500 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700501 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700502}
503
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700504void MetricsDaemon::StatsReporterInit() {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800505 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700506 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800507 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700508 stats_state_ = kStatsLong;
509 stats_initial_time_ = GetActiveTime();
510 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700511 LOG(WARNING) << "not collecting disk stats";
512 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700513 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700514 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800515}
516
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700517void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800518 if (testing_) {
519 return;
520 }
Steve Funge86591e2014-12-01 13:38:21 -0800521 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
522 base::Bind(&MetricsDaemon::StatsCallback, base::Unretained(this)),
523 base::TimeDelta::FromSeconds(wait));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800524}
525
Ben Chanf05ab402014-08-07 00:54:59 -0700526bool MetricsDaemon::DiskStatsReadStats(uint64_t* read_sectors,
527 uint64_t* write_sectors) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800528 int nchars;
529 int nitems;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700530 bool success = false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800531 char line[200];
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700532 if (diskstats_path_.empty()) {
533 return false;
534 }
Luigi Semenzato0f132bb2011-02-28 11:17:43 -0800535 int file = HANDLE_EINTR(open(diskstats_path_.c_str(), O_RDONLY));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800536 if (file < 0) {
537 PLOG(WARNING) << "cannot open " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700538 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800539 }
540 nchars = HANDLE_EINTR(read(file, line, sizeof(line)));
541 if (nchars < 0) {
542 PLOG(WARNING) << "cannot read from " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700543 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800544 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700545 LOG_IF(WARNING, nchars == sizeof(line))
546 << "line too long in " << diskstats_path_;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800547 line[nchars] = '\0';
Nathan Bullockdc1ef3c2014-09-17 09:24:10 -0400548 nitems = sscanf(line, "%*d %*d %" PRIu64 " %*d %*d %*d %" PRIu64,
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800549 read_sectors, write_sectors);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700550 if (nitems == 2) {
551 success = true;
552 } else {
553 LOG(WARNING) << "found " << nitems << " items in "
554 << diskstats_path_ << ", expected 2";
555 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800556 }
Mike Frysinger3e8a8512014-05-14 16:14:37 -0400557 IGNORE_EINTR(close(file));
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700558 return success;
559}
560
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700561bool MetricsDaemon::VmStatsParseStats(const char* stats,
562 struct VmstatRecord* record) {
563 // a mapping of string name to field in VmstatRecord and whether we found it
564 struct mapping {
565 const string name;
566 uint64_t* value_p;
567 bool found;
568 } map[] =
569 { { .name = "pgmajfault",
570 .value_p = &record->page_faults_,
571 .found = false },
572 { .name = "pswpin",
573 .value_p = &record->swap_in_,
574 .found = false },
575 { .name = "pswpout",
576 .value_p = &record->swap_out_,
577 .found = false }, };
578
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700579 // Each line in the file has the form
580 // <ID> <VALUE>
581 // for instance:
582 // nr_free_pages 213427
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700583 vector<string> lines;
584 Tokenize(stats, "\n", &lines);
585 for (vector<string>::iterator it = lines.begin();
586 it != lines.end(); ++it) {
587 vector<string> tokens;
588 base::SplitString(*it, ' ', &tokens);
589 if (tokens.size() == 2) {
590 for (unsigned int i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
591 if (!tokens[0].compare(map[i].name)) {
592 if (!base::StringToUint64(tokens[1], map[i].value_p))
593 return false;
594 map[i].found = true;
595 }
596 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700597 } else {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700598 LOG(WARNING) << "unexpected vmstat format";
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700599 }
600 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700601 // make sure we got all the stats
602 for (unsigned i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
603 if (map[i].found == false) {
604 LOG(WARNING) << "vmstat missing " << map[i].name;
605 return false;
606 }
607 }
608 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700609}
610
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700611bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
612 string value_string;
613 FilePath* path = new FilePath(vmstats_path_);
Ben Chan2e6543d2014-02-05 23:26:25 -0800614 if (!base::ReadFileToString(*path, &value_string)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700615 delete path;
616 LOG(WARNING) << "cannot read " << vmstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700617 return false;
618 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700619 delete path;
620 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800621}
622
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700623bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700624 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700625 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800626 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700627 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
628 return false;
629 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800630 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700631 LOG(WARNING) << "no newline in " << value_string;
632 // Continue even though the lack of newline is suspicious.
633 }
634 if (!base::StringToInt(value_string, value)) {
635 LOG(WARNING) << "cannot convert " << value_string << " to int";
636 return false;
637 }
638 return true;
639}
640
641void MetricsDaemon::SendCpuThrottleMetrics() {
642 // |max_freq| is 0 only the first time through.
643 static int max_freq = 0;
644 if (max_freq == -1)
645 // Give up, as sysfs did not report max_freq correctly.
646 return;
647 if (max_freq == 0 || testing_) {
648 // One-time initialization of max_freq. (Every time when testing.)
649 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
650 max_freq = -1;
651 return;
652 }
653 if (max_freq == 0) {
654 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
655 max_freq = -1;
656 return;
657 }
658 if (max_freq % 10000 == 1000) {
659 // Special case: system has turbo mode, and max non-turbo frequency is
660 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
661 // being multiples of (at least) 10 MHz. Although there is no guarantee
662 // of this, it seems a fairly reasonable assumption. Otherwise we should
663 // read scaling_available_frequencies, sort the frequencies, compare the
664 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
665 // hack too, no telling when it will change).
666 max_freq -= 1000;
667 }
668 }
669 int scaled_freq = 0;
670 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
671 return;
672 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
673 // scaled_freq is not the actual turbo frequency. We indicate this situation
674 // with a 101% value.
675 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800676 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700677}
678
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700679// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700680
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700681void MetricsDaemon::StatsCallback() {
Ben Chanf05ab402014-08-07 00:54:59 -0700682 uint64_t read_sectors_now, write_sectors_now;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700683 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700684 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700685 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700686 if (testing_) {
687 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700688 delta_time = stats_state_ == kStatsShort ?
689 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700690 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700691 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
692 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700693 int delta_read = read_sectors_now - read_sectors_;
694 int delta_write = write_sectors_now - write_sectors_;
695 int read_sectors_per_second = delta_read / delta_time;
696 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700697 bool vmstats_success = VmStatsReadStats(&vmstats_now);
698 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
699 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
700 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
701 uint64_t page_faults_per_second = delta_faults / delta_time;
702 uint64_t swap_in_per_second = delta_swap_in / delta_time;
703 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800704
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700705 switch (stats_state_) {
706 case kStatsShort:
707 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800708 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700709 read_sectors_per_second,
710 1,
711 kMetricSectorsIOMax,
712 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800713 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700714 write_sectors_per_second,
715 1,
716 kMetricSectorsIOMax,
717 kMetricSectorsBuckets);
718 }
719 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800720 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700721 page_faults_per_second,
722 1,
723 kMetricPageFaultsMax,
724 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800725 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700726 swap_in_per_second,
727 1,
728 kMetricPageFaultsMax,
729 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800730 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700731 swap_out_per_second,
732 1,
733 kMetricPageFaultsMax,
734 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700735 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800736 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700737 stats_state_ = kStatsLong;
738 ScheduleStatsCallback(kMetricStatsLongInterval -
739 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800740 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700741 case kStatsLong:
742 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800743 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700744 read_sectors_per_second,
745 1,
746 kMetricSectorsIOMax,
747 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800748 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700749 write_sectors_per_second,
750 1,
751 kMetricSectorsIOMax,
752 kMetricSectorsBuckets);
753 // Reset sector counters.
754 read_sectors_ = read_sectors_now;
755 write_sectors_ = write_sectors_now;
756 }
757 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800758 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700759 page_faults_per_second,
760 1,
761 kMetricPageFaultsMax,
762 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800763 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700764 swap_in_per_second,
765 1,
766 kMetricPageFaultsMax,
767 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800768 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700769 swap_out_per_second,
770 1,
771 kMetricPageFaultsMax,
772 kMetricPageFaultsBuckets);
773
774 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700775 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700776 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700777 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700778 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800779 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700780 stats_state_ = kStatsShort;
781 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800782 break;
783 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700784 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800785 }
786}
787
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700788void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
789 if (testing_) {
790 return;
791 }
Steve Funge86591e2014-12-01 13:38:21 -0800792 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
793 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
794 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800795 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800796 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700797}
798
Steve Funge86591e2014-12-01 13:38:21 -0800799void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700800 string meminfo_raw;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700801 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800802 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700803 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800804 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700805 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700806 // Make both calls even if the first one fails.
807 bool success = ProcessMeminfo(meminfo_raw);
Steve Funge86591e2014-12-01 13:38:21 -0800808 bool reschedule =
809 ReportZram(base::FilePath(FILE_PATH_LITERAL("/sys/block/zram0"))) &&
Luigi Semenzato96360192014-06-04 10:53:35 -0700810 success;
Steve Funge86591e2014-12-01 13:38:21 -0800811 if (reschedule) {
812 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
813 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800814 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800815 wait);
816 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700817}
818
819// static
820bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700821 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700822 std::string content;
823 if (!base::ReadFileToString(path, &content)) {
824 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
825 return false;
826 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700827 // Remove final newline.
828 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700829 if (!base::StringToUint64(content, value)) {
830 LOG(WARNING) << "invalid integer: " << content;
831 return false;
832 }
833 return true;
834}
835
836bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
837 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700838 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700839 const size_t page_size = 4096;
840
841 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
842 &compr_data_size) ||
843 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
844 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
845 return false;
846 }
847
848 // |orig_data_size| does not include zero-filled pages.
849 orig_data_size += zero_pages * page_size;
850
851 const int compr_data_size_mb = compr_data_size >> 20;
852 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
853 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
854
855 // Report compressed size in megabytes. 100 MB or less has little impact.
856 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
857 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
858 // The compression ratio is multiplied by 100 for better resolution. The
859 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
860 // don't want samples when very little memory is being compressed.
861 if (compr_data_size_mb >= 1) {
862 SendSample("Platform.ZramCompressionRatioPercent",
863 orig_data_size * 100 / compr_data_size, 100, 600, 50);
864 }
865 // The values of interest for zero_pages are between 1MB and 1GB. The units
866 // are number of pages.
867 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
868 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
869
870 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700871}
872
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700873bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700874 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700875 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
876 { "MemFree", "MemFree" },
877 { "Buffers", "Buffers" },
878 { "Cached", "Cached" },
879 // { "SwapCached", "SwapCached" },
880 { "Active", "Active" },
881 { "Inactive", "Inactive" },
882 { "ActiveAnon", "Active(anon)" },
883 { "InactiveAnon", "Inactive(anon)" },
884 { "ActiveFile" , "Active(file)" },
885 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800886 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700887 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800888 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
889 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700890 // { "Dirty", "Dirty" },
891 // { "Writeback", "Writeback" },
892 { "AnonPages", "AnonPages" },
893 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800894 { "Shmem", "Shmem", kMeminfoOp_HistLog },
895 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700896 // { "SReclaimable", "SReclaimable" },
897 // { "SUnreclaim", "SUnreclaim" },
898 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700899 vector<MeminfoRecord> fields(fields_array,
900 fields_array + arraysize(fields_array));
901 if (!FillMeminfo(meminfo_raw, &fields)) {
902 return false;
903 }
904 int total_memory = fields[0].value;
905 if (total_memory == 0) {
906 // this "cannot happen"
907 LOG(WARNING) << "borked meminfo parser";
908 return false;
909 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800910 int swap_total = 0;
911 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700912 // Send all fields retrieved, except total memory.
913 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800914 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
915 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800916 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800917 switch (fields[i].op) {
918 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800919 // report value as percent of total memory
920 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800921 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800922 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800923 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800924 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800925 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800926 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800927 case kMeminfoOp_SwapTotal:
928 swap_total = fields[i].value;
929 case kMeminfoOp_SwapFree:
930 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800931 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700932 }
933 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800934 if (swap_total > 0) {
935 int swap_used = swap_total - swap_free;
936 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800937 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
938 SendLinearSample("Platform.MeminfoSwapUsedPercent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800939 100, 101);
940 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700941 return true;
942}
943
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700944bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
945 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700946 vector<string> lines;
947 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700948
949 // Scan meminfo output and collect field values. Each field name has to
950 // match a meminfo entry (case insensitive) after removing non-alpha
951 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700952 unsigned int ifield = 0;
953 for (unsigned int iline = 0;
954 iline < nlines && ifield < fields->size();
955 iline++) {
956 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700957 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700958 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
959 // Name matches. Parse value and save.
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700960 char* rest;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700961 (*fields)[ifield].value =
962 static_cast<int>(strtol(tokens[1].c_str(), &rest, 10));
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700963 if (*rest != '\0') {
964 LOG(WARNING) << "missing meminfo value";
965 return false;
966 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700967 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700968 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700969 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700970 if (ifield < fields->size()) {
971 // End of input reached while scanning.
972 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
973 << " and following";
974 return false;
975 }
976 return true;
977}
978
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800979void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700980 if (testing_) {
981 return;
982 }
Steve Funge86591e2014-12-01 13:38:21 -0800983 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
984 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
985 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700986}
987
988void MetricsDaemon::MemuseCallback() {
989 // Since we only care about active time (i.e. uptime minus sleep time) but
990 // the callbacks are driven by real time (uptime), we check if we should
991 // reschedule this callback due to intervening sleep periods.
992 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800993 // Avoid intervals of less than one second.
994 double remaining_time = ceil(memuse_final_time_ - now);
995 if (remaining_time > 0) {
996 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700997 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800998 // Report stats and advance the measurement interval unless there are
999 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -07001000 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001001 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
1002 double interval = kMemuseIntervals[memuse_interval_index_++];
1003 memuse_final_time_ = now + interval;
1004 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001005 }
1006 }
1007}
1008
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001009bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001010 string meminfo_raw;
1011 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -08001012 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001013 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
1014 return false;
1015 }
1016 return ProcessMemuse(meminfo_raw);
1017}
1018
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001019bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001020 static const MeminfoRecord fields_array[] = {
1021 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
1022 { "ActiveAnon", "Active(anon)" },
1023 { "InactiveAnon", "Inactive(anon)" },
1024 };
1025 vector<MeminfoRecord> fields(fields_array,
1026 fields_array + arraysize(fields_array));
1027 if (!FillMeminfo(meminfo_raw, &fields)) {
1028 return false;
1029 }
1030 int total = fields[0].value;
1031 int active_anon = fields[1].value;
1032 int inactive_anon = fields[2].value;
1033 if (total == 0) {
1034 // this "cannot happen"
1035 LOG(WARNING) << "borked meminfo parser";
1036 return false;
1037 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -08001038 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
1039 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001040 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -07001041 100, 101);
1042 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001043}
1044
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001045void MetricsDaemon::ReportDailyUse(int use_seconds) {
1046 if (use_seconds <= 0)
Darin Petkov1bb904e2010-06-16 15:58:06 -07001047 return;
1048
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001049 int minutes = (use_seconds + kSecondsPerMinute / 2) / kSecondsPerMinute;
1050 SendSample("Logging.DailyUseTime",
1051 minutes,
1052 1,
1053 kMinutesPerDay * 30 * 2, // cumulative---two months worth
1054 50);
Darin Petkovf1e85e42010-06-10 15:59:53 -07001055}
1056
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001057void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -07001058 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -07001059 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -07001060}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001061
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001062void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001063 // Report the number of crashes for this OS version, but don't clear the
1064 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -07001065 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001066 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001067 crashes_count,
1068 1, // value of first bucket
1069 500, // value of last bucket
1070 100); // number of buckets
1071
1072
Ben Chanf05ab402014-08-07 00:54:59 -07001073 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001074 SendSample(version_cumulative_cpu_use_->Name(),
1075 cpu_use_ms / 1000, // stat is in seconds
1076 1, // device may be used very little...
1077 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
1078 100);
1079
1080 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
1081 // can be zero. Avoid division by zero.
1082 if (cpu_use_ms > 0) {
1083 // Send the crash frequency since update in number of crashes per CPU year.
1084 SendSample("Logging.KernelCrashesPerCpuYear",
1085 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
1086 1,
1087 1000 * 1000, // about one crash every 30s of CPU time
1088 100);
1089 }
1090
Ben Chanf05ab402014-08-07 00:54:59 -07001091 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001092 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001093 SendSample(version_cumulative_active_use_->Name(),
1094 active_use_seconds / 1000, // stat is in seconds
1095 1, // device may be used very little...
1096 8 * 1000 * 1000, // ... or a lot (about 90 days)
1097 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001098 // Same as above, but per year of active time.
1099 SendSample("Logging.KernelCrashesPerActiveYear",
1100 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
1101 1,
1102 1000 * 1000, // about one crash every 30s of active time
1103 100);
1104 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001105}
1106
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001107void MetricsDaemon::SendDailyUseSample(
1108 const scoped_ptr<PersistentInteger>& use) {
1109 SendSample(use->Name(),
1110 use->GetAndClear(),
1111 1, // value of first bucket
1112 kSecondsPerDay, // value of last bucket
1113 50); // number of buckets
1114}
1115
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001116void MetricsDaemon::SendCrashIntervalSample(
1117 const scoped_ptr<PersistentInteger>& interval) {
1118 SendSample(interval->Name(),
1119 interval->GetAndClear(),
1120 1, // value of first bucket
1121 4 * kSecondsPerWeek, // value of last bucket
1122 50); // number of buckets
1123}
1124
1125void MetricsDaemon::SendCrashFrequencySample(
1126 const scoped_ptr<PersistentInteger>& frequency) {
1127 SendSample(frequency->Name(),
1128 frequency->GetAndClear(),
1129 1, // value of first bucket
1130 100, // value of last bucket
1131 50); // number of buckets
1132}
1133
1134void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001135 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001136 // TODO(semenzato): add a proper linear histogram to the Chrome external
1137 // metrics API.
1138 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1139 metrics_lib_->SendEnumToUMA(name, sample, max);
1140}
Daniel Eratc83975a2014-04-04 08:53:44 -07001141
1142void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
1143 Time now_wall_time) {
1144 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001145 daily_active_use_->Add(elapsed_seconds);
1146 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -07001147 user_crash_interval_->Add(elapsed_seconds);
1148 kernel_crash_interval_->Add(elapsed_seconds);
1149 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
1150 last_update_stats_time_ = now_ticks;
1151
1152 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
1153 const int day = since_epoch.InDays();
1154 const int week = day / 7;
1155
1156 if (daily_cycle_->Get() != day) {
1157 daily_cycle_->Set(day);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001158 SendDailyUseSample(daily_active_use_);
1159 SendDailyUseSample(version_cumulative_active_use_);
Daniel Eratc83975a2014-04-04 08:53:44 -07001160 SendCrashFrequencySample(any_crashes_daily_count_);
1161 SendCrashFrequencySample(user_crashes_daily_count_);
1162 SendCrashFrequencySample(kernel_crashes_daily_count_);
1163 SendCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001164 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -07001165 }
1166
1167 if (weekly_cycle_->Get() != week) {
1168 weekly_cycle_->Set(week);
1169 SendCrashFrequencySample(any_crashes_weekly_count_);
1170 SendCrashFrequencySample(user_crashes_weekly_count_);
1171 SendCrashFrequencySample(kernel_crashes_weekly_count_);
1172 SendCrashFrequencySample(unclean_shutdowns_weekly_count_);
1173 }
1174}
1175
Steve Funge86591e2014-12-01 13:38:21 -08001176void MetricsDaemon::HandleUpdateStatsTimeout() {
1177 UpdateStats(TimeTicks::Now(), Time::Now());
1178 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
1179 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
1180 base::Unretained(this)),
1181 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -07001182}