blob: 4ea899f5135f1ea27fc0bd3e74124458f05409e7 [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_),
Bertrand SIMONNETe4fa61e2015-02-18 09:38:55 -0800194 metrics_lib_,
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700195 server_));
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700196 upload_service_->Init(upload_interval_, metrics_file_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700197 upload_service_->UploadEvent();
198}
199
Ben Chanf05ab402014-08-07 00:54:59 -0700200uint32_t MetricsDaemon::GetOsVersionHash() {
201 static uint32_t cached_version_hash = 0;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800202 static bool version_hash_is_cached = false;
203 if (version_hash_is_cached)
204 return cached_version_hash;
205 version_hash_is_cached = true;
206 std::string version;
207 if (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_VERSION", &version)) {
208 cached_version_hash = base::Hash(version);
209 } else if (testing_) {
210 cached_version_hash = 42; // return any plausible value for the hash
211 } else {
212 LOG(FATAL) << "could not find CHROMEOS_RELEASE_VERSION";
213 }
214 return cached_version_hash;
215}
216
Ben Chan067ec8b2015-02-17 13:54:04 -0800217bool MetricsDaemon::IsOnOfficialBuild() const {
218 std::string build_type;
219 return (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_BUILD_TYPE",
220 &build_type) &&
221 build_type == kOfficialBuild);
222}
223
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700224void MetricsDaemon::Init(bool testing,
225 bool uploader_active,
226 MetricsLibraryInterface* metrics_lib,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700227 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700228 const string& vmstats_path,
229 const string& scaling_max_freq_path,
Steve Fung67906c62014-10-06 15:15:30 -0700230 const string& cpuinfo_max_freq_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700231 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700232 const string& server,
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700233 const string& metrics_file,
234 const string& config_root) {
Darin Petkov65b01462010-04-14 13:32:20 -0700235 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800236 uploader_active_ = uploader_active;
Bertrand SIMONNET71a62ef2014-10-07 11:26:25 -0700237 config_root_ = config_root;
Alex Vakulenko14595032014-08-28 14:59:56 -0700238 DCHECK(metrics_lib != nullptr);
Darin Petkovfc91b422010-05-12 13:05:45 -0700239 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700240
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700241 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700242 server_ = server;
243 metrics_file_ = metrics_file;
244
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700245 // Get ticks per second (HZ) on this system.
246 // Sysconf cannot fail, so no sanity checks are needed.
247 ticks_per_second_ = sysconf(_SC_CLK_TCK);
248
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700249 daily_active_use_.reset(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800250 new PersistentInteger("Logging.DailyUseTime"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700251 version_cumulative_active_use_.reset(
252 new PersistentInteger("Logging.CumulativeDailyUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700253 version_cumulative_cpu_use_.reset(
254 new PersistentInteger("Logging.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700255
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800256 kernel_crash_interval_.reset(
257 new PersistentInteger("Logging.KernelCrashInterval"));
258 unclean_shutdown_interval_.reset(
259 new PersistentInteger("Logging.UncleanShutdownInterval"));
260 user_crash_interval_.reset(
261 new PersistentInteger("Logging.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700262
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800263 any_crashes_daily_count_.reset(
264 new PersistentInteger("Logging.AnyCrashesDaily"));
265 any_crashes_weekly_count_.reset(
266 new PersistentInteger("Logging.AnyCrashesWeekly"));
267 user_crashes_daily_count_.reset(
268 new PersistentInteger("Logging.UserCrashesDaily"));
269 user_crashes_weekly_count_.reset(
270 new PersistentInteger("Logging.UserCrashesWeekly"));
271 kernel_crashes_daily_count_.reset(
272 new PersistentInteger("Logging.KernelCrashesDaily"));
273 kernel_crashes_weekly_count_.reset(
274 new PersistentInteger("Logging.KernelCrashesWeekly"));
275 kernel_crashes_version_count_.reset(
276 new PersistentInteger("Logging.KernelCrashesSinceUpdate"));
277 unclean_shutdowns_daily_count_.reset(
278 new PersistentInteger("Logging.UncleanShutdownsDaily"));
279 unclean_shutdowns_weekly_count_.reset(
280 new PersistentInteger("Logging.UncleanShutdownsWeekly"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700281
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800282 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
283 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
284 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800285
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700286 diskstats_path_ = diskstats_path;
287 vmstats_path_ = vmstats_path;
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700288 scaling_max_freq_path_ = scaling_max_freq_path;
289 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Steve Funge86591e2014-12-01 13:38:21 -0800290
291 // If testing, initialize Stats Reporter without connecting DBus
292 if (testing_)
293 StatsReporterInit();
294}
295
296int MetricsDaemon::OnInit() {
297 int return_code = chromeos::DBusDaemon::OnInit();
298 if (return_code != EX_OK)
299 return return_code;
300
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700301 StatsReporterInit();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800302
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700303 // Start collecting meminfo stats.
304 ScheduleMeminfoCallback(kMetricMeminfoInterval);
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800305 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
306 ScheduleMemuseCallback(kMemuseIntervals[0]);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700307
Steve Funge86591e2014-12-01 13:38:21 -0800308 if (testing_)
309 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700310
Steve Funge86591e2014-12-01 13:38:21 -0800311 bus_->AssertOnDBusThread();
312 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700313
Steve Funge86591e2014-12-01 13:38:21 -0800314 if (bus_->is_connected()) {
315 const std::string match_rule =
316 base::StringPrintf(kCrashReporterMatchRule,
317 kCrashReporterInterface,
318 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700319
Steve Funge86591e2014-12-01 13:38:21 -0800320 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700321
Steve Funge86591e2014-12-01 13:38:21 -0800322 DBusError error;
323 dbus_error_init(&error);
324 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700325
Steve Funge86591e2014-12-01 13:38:21 -0800326 if (dbus_error_is_set(&error)) {
327 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
328 << error.name << ": " << error.message;
329 return EX_SOFTWARE;
330 }
331 } else {
332 LOG(ERROR) << "DBus isn't connected.";
333 return EX_UNAVAILABLE;
Darin Petkov703ec972010-04-27 11:02:18 -0700334 }
335
Steve Funge86591e2014-12-01 13:38:21 -0800336 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
337 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
338 base::Unretained(this)),
339 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -0700340
Steve Funge86591e2014-12-01 13:38:21 -0800341 if (uploader_active_) {
Ben Chan067ec8b2015-02-17 13:54:04 -0800342 if (IsOnOfficialBuild()) {
343 LOG(INFO) << "uploader enabled";
344 upload_service_.reset(
Bertrand SIMONNETe4fa61e2015-02-18 09:38:55 -0800345 new UploadService(new SystemProfileCache(), metrics_lib_, server_));
Ben Chan067ec8b2015-02-17 13:54:04 -0800346 upload_service_->Init(upload_interval_, metrics_file_);
347 } else {
348 LOG(INFO) << "uploader disabled on non-official build";
349 }
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700350 }
Steve Funge86591e2014-12-01 13:38:21 -0800351
352 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700353}
354
Steve Funge86591e2014-12-01 13:38:21 -0800355void MetricsDaemon::OnShutdown(int* return_code) {
356 if (!testing_ && bus_->is_connected()) {
357 const std::string match_rule =
358 base::StringPrintf(kCrashReporterMatchRule,
359 kCrashReporterInterface,
360 kCrashReporterUserCrashSignal);
361
362 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
363
364 DBusError error;
365 dbus_error_init(&error);
366 bus_->RemoveMatch(match_rule, &error);
367
368 if (dbus_error_is_set(&error)) {
369 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
370 << error.name << ": " << error.message;
371 }
372 }
373 chromeos::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700374}
375
Darin Petkov703ec972010-04-27 11:02:18 -0700376// static
377DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
378 DBusMessage* message,
379 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700380 int message_type = dbus_message_get_type(message);
381 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700382 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700383 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
384 }
385
386 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700387 const std::string interface(dbus_message_get_interface(message));
388 const std::string member(dbus_message_get_member(message));
389 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700390
391 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
392
393 DBusMessageIter iter;
394 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700395 if (interface == kCrashReporterInterface) {
396 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700397 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700398 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700399 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700400 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
401 }
402
403 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700404}
405
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700406// One might argue that parts of this should go into
407// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
408
409TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700410 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
411 std::string proc_stat_string;
412 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
413 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
414 return TimeDelta();
415 }
416
417 std::vector<std::string> proc_stat_lines;
418 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
419 if (proc_stat_lines.empty()) {
420 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
421 << ": " << proc_stat_string;
422 return TimeDelta();
423 }
424 std::vector<std::string> proc_stat_totals;
425 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
426
Ben Chanf05ab402014-08-07 00:54:59 -0700427 uint64_t user_ticks, user_nice_ticks, system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700428 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
429 proc_stat_totals[0] != "cpu" ||
430 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
431 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
432 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
433 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
434 return TimeDelta(base::TimeDelta::FromSeconds(0));
435 }
436
Ben Chanf05ab402014-08-07 00:54:59 -0700437 uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700438
439 // Sanity check.
440 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
441 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
442 << " to " << total_cpu_use_ticks;
443 return TimeDelta();
444 }
445
Ben Chanf05ab402014-08-07 00:54:59 -0700446 uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700447 latest_cpu_use_ticks_ = total_cpu_use_ticks;
448 // Use microseconds to avoid significant truncations.
449 return base::TimeDelta::FromMicroseconds(
450 diff * 1000 * 1000 / ticks_per_second_);
451}
452
Darin Petkov1bb904e2010-06-16 15:58:06 -0700453void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700454 // Counts the active time up to now.
455 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700456
457 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800458 SendCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700459
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800460 any_crashes_daily_count_->Add(1);
461 any_crashes_weekly_count_->Add(1);
462 user_crashes_daily_count_->Add(1);
463 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700464}
465
Darin Petkov38d5cb02010-06-24 12:10:26 -0700466void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700467 // Counts the active time up to now.
468 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700469
470 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800471 SendCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700472
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800473 any_crashes_daily_count_->Add(1);
474 any_crashes_weekly_count_->Add(1);
475 kernel_crashes_daily_count_->Add(1);
476 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800477
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800478 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700479}
480
Ken Mixterccd84c02010-08-16 19:57:13 -0700481void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700482 // Counts the active time up to now.
483 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700484
485 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800486 SendCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700487
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800488 unclean_shutdowns_daily_count_->Add(1);
489 unclean_shutdowns_weekly_count_->Add(1);
490 any_crashes_daily_count_->Add(1);
491 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700492}
493
Luigi Semenzato8accd332011-05-17 16:37:18 -0700494bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700495 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800496 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700497 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700498
499 // Deletes the crash-detected file so that the daemon doesn't report
500 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800501 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700502 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700503}
504
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700505void MetricsDaemon::StatsReporterInit() {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800506 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700507 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800508 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700509 stats_state_ = kStatsLong;
510 stats_initial_time_ = GetActiveTime();
511 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700512 LOG(WARNING) << "not collecting disk stats";
513 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700514 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700515 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800516}
517
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700518void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800519 if (testing_) {
520 return;
521 }
Steve Funge86591e2014-12-01 13:38:21 -0800522 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
523 base::Bind(&MetricsDaemon::StatsCallback, base::Unretained(this)),
524 base::TimeDelta::FromSeconds(wait));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800525}
526
Ben Chanf05ab402014-08-07 00:54:59 -0700527bool MetricsDaemon::DiskStatsReadStats(uint64_t* read_sectors,
528 uint64_t* write_sectors) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800529 int nchars;
530 int nitems;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700531 bool success = false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800532 char line[200];
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700533 if (diskstats_path_.empty()) {
534 return false;
535 }
Luigi Semenzato0f132bb2011-02-28 11:17:43 -0800536 int file = HANDLE_EINTR(open(diskstats_path_.c_str(), O_RDONLY));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800537 if (file < 0) {
538 PLOG(WARNING) << "cannot open " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700539 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800540 }
541 nchars = HANDLE_EINTR(read(file, line, sizeof(line)));
542 if (nchars < 0) {
543 PLOG(WARNING) << "cannot read from " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700544 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800545 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700546 LOG_IF(WARNING, nchars == sizeof(line))
547 << "line too long in " << diskstats_path_;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800548 line[nchars] = '\0';
Nathan Bullockdc1ef3c2014-09-17 09:24:10 -0400549 nitems = sscanf(line, "%*d %*d %" PRIu64 " %*d %*d %*d %" PRIu64,
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800550 read_sectors, write_sectors);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700551 if (nitems == 2) {
552 success = true;
553 } else {
554 LOG(WARNING) << "found " << nitems << " items in "
555 << diskstats_path_ << ", expected 2";
556 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800557 }
Mike Frysinger3e8a8512014-05-14 16:14:37 -0400558 IGNORE_EINTR(close(file));
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700559 return success;
560}
561
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700562bool MetricsDaemon::VmStatsParseStats(const char* stats,
563 struct VmstatRecord* record) {
564 // a mapping of string name to field in VmstatRecord and whether we found it
565 struct mapping {
566 const string name;
567 uint64_t* value_p;
568 bool found;
569 } map[] =
570 { { .name = "pgmajfault",
571 .value_p = &record->page_faults_,
572 .found = false },
573 { .name = "pswpin",
574 .value_p = &record->swap_in_,
575 .found = false },
576 { .name = "pswpout",
577 .value_p = &record->swap_out_,
578 .found = false }, };
579
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700580 // Each line in the file has the form
581 // <ID> <VALUE>
582 // for instance:
583 // nr_free_pages 213427
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700584 vector<string> lines;
585 Tokenize(stats, "\n", &lines);
586 for (vector<string>::iterator it = lines.begin();
587 it != lines.end(); ++it) {
588 vector<string> tokens;
589 base::SplitString(*it, ' ', &tokens);
590 if (tokens.size() == 2) {
591 for (unsigned int i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
592 if (!tokens[0].compare(map[i].name)) {
593 if (!base::StringToUint64(tokens[1], map[i].value_p))
594 return false;
595 map[i].found = true;
596 }
597 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700598 } else {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700599 LOG(WARNING) << "unexpected vmstat format";
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700600 }
601 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700602 // make sure we got all the stats
603 for (unsigned i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
604 if (map[i].found == false) {
605 LOG(WARNING) << "vmstat missing " << map[i].name;
606 return false;
607 }
608 }
609 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700610}
611
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700612bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
613 string value_string;
614 FilePath* path = new FilePath(vmstats_path_);
Ben Chan2e6543d2014-02-05 23:26:25 -0800615 if (!base::ReadFileToString(*path, &value_string)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700616 delete path;
617 LOG(WARNING) << "cannot read " << vmstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700618 return false;
619 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700620 delete path;
621 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800622}
623
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700624bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700625 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700626 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800627 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700628 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
629 return false;
630 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800631 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700632 LOG(WARNING) << "no newline in " << value_string;
633 // Continue even though the lack of newline is suspicious.
634 }
635 if (!base::StringToInt(value_string, value)) {
636 LOG(WARNING) << "cannot convert " << value_string << " to int";
637 return false;
638 }
639 return true;
640}
641
642void MetricsDaemon::SendCpuThrottleMetrics() {
643 // |max_freq| is 0 only the first time through.
644 static int max_freq = 0;
645 if (max_freq == -1)
646 // Give up, as sysfs did not report max_freq correctly.
647 return;
648 if (max_freq == 0 || testing_) {
649 // One-time initialization of max_freq. (Every time when testing.)
650 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
651 max_freq = -1;
652 return;
653 }
654 if (max_freq == 0) {
655 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
656 max_freq = -1;
657 return;
658 }
659 if (max_freq % 10000 == 1000) {
660 // Special case: system has turbo mode, and max non-turbo frequency is
661 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
662 // being multiples of (at least) 10 MHz. Although there is no guarantee
663 // of this, it seems a fairly reasonable assumption. Otherwise we should
664 // read scaling_available_frequencies, sort the frequencies, compare the
665 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
666 // hack too, no telling when it will change).
667 max_freq -= 1000;
668 }
669 }
670 int scaled_freq = 0;
671 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
672 return;
673 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
674 // scaled_freq is not the actual turbo frequency. We indicate this situation
675 // with a 101% value.
676 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800677 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700678}
679
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700680// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700681
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700682void MetricsDaemon::StatsCallback() {
Ben Chanf05ab402014-08-07 00:54:59 -0700683 uint64_t read_sectors_now, write_sectors_now;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700684 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700685 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700686 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700687 if (testing_) {
688 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700689 delta_time = stats_state_ == kStatsShort ?
690 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700691 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700692 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
693 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700694 int delta_read = read_sectors_now - read_sectors_;
695 int delta_write = write_sectors_now - write_sectors_;
696 int read_sectors_per_second = delta_read / delta_time;
697 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700698 bool vmstats_success = VmStatsReadStats(&vmstats_now);
699 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
700 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
701 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
702 uint64_t page_faults_per_second = delta_faults / delta_time;
703 uint64_t swap_in_per_second = delta_swap_in / delta_time;
704 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800705
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700706 switch (stats_state_) {
707 case kStatsShort:
708 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800709 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700710 read_sectors_per_second,
711 1,
712 kMetricSectorsIOMax,
713 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800714 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700715 write_sectors_per_second,
716 1,
717 kMetricSectorsIOMax,
718 kMetricSectorsBuckets);
719 }
720 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800721 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700722 page_faults_per_second,
723 1,
724 kMetricPageFaultsMax,
725 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800726 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700727 swap_in_per_second,
728 1,
729 kMetricPageFaultsMax,
730 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800731 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700732 swap_out_per_second,
733 1,
734 kMetricPageFaultsMax,
735 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700736 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800737 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700738 stats_state_ = kStatsLong;
739 ScheduleStatsCallback(kMetricStatsLongInterval -
740 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800741 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700742 case kStatsLong:
743 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800744 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700745 read_sectors_per_second,
746 1,
747 kMetricSectorsIOMax,
748 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800749 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700750 write_sectors_per_second,
751 1,
752 kMetricSectorsIOMax,
753 kMetricSectorsBuckets);
754 // Reset sector counters.
755 read_sectors_ = read_sectors_now;
756 write_sectors_ = write_sectors_now;
757 }
758 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800759 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700760 page_faults_per_second,
761 1,
762 kMetricPageFaultsMax,
763 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800764 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700765 swap_in_per_second,
766 1,
767 kMetricPageFaultsMax,
768 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800769 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700770 swap_out_per_second,
771 1,
772 kMetricPageFaultsMax,
773 kMetricPageFaultsBuckets);
774
775 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700776 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700777 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700778 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700779 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800780 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700781 stats_state_ = kStatsShort;
782 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800783 break;
784 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700785 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800786 }
787}
788
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700789void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
790 if (testing_) {
791 return;
792 }
Steve Funge86591e2014-12-01 13:38:21 -0800793 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
794 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
795 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800796 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800797 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700798}
799
Steve Funge86591e2014-12-01 13:38:21 -0800800void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700801 string meminfo_raw;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700802 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800803 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700804 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800805 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700806 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700807 // Make both calls even if the first one fails.
808 bool success = ProcessMeminfo(meminfo_raw);
Steve Funge86591e2014-12-01 13:38:21 -0800809 bool reschedule =
810 ReportZram(base::FilePath(FILE_PATH_LITERAL("/sys/block/zram0"))) &&
Luigi Semenzato96360192014-06-04 10:53:35 -0700811 success;
Steve Funge86591e2014-12-01 13:38:21 -0800812 if (reschedule) {
813 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
814 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800815 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800816 wait);
817 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700818}
819
820// static
821bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700822 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700823 std::string content;
824 if (!base::ReadFileToString(path, &content)) {
825 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
826 return false;
827 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700828 // Remove final newline.
829 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700830 if (!base::StringToUint64(content, value)) {
831 LOG(WARNING) << "invalid integer: " << content;
832 return false;
833 }
834 return true;
835}
836
837bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
838 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700839 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700840 const size_t page_size = 4096;
841
842 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
843 &compr_data_size) ||
844 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
845 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
846 return false;
847 }
848
849 // |orig_data_size| does not include zero-filled pages.
850 orig_data_size += zero_pages * page_size;
851
852 const int compr_data_size_mb = compr_data_size >> 20;
853 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
854 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
855
856 // Report compressed size in megabytes. 100 MB or less has little impact.
857 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
858 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
859 // The compression ratio is multiplied by 100 for better resolution. The
860 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
861 // don't want samples when very little memory is being compressed.
862 if (compr_data_size_mb >= 1) {
863 SendSample("Platform.ZramCompressionRatioPercent",
864 orig_data_size * 100 / compr_data_size, 100, 600, 50);
865 }
866 // The values of interest for zero_pages are between 1MB and 1GB. The units
867 // are number of pages.
868 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
869 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
870
871 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700872}
873
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700874bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700875 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700876 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
877 { "MemFree", "MemFree" },
878 { "Buffers", "Buffers" },
879 { "Cached", "Cached" },
880 // { "SwapCached", "SwapCached" },
881 { "Active", "Active" },
882 { "Inactive", "Inactive" },
883 { "ActiveAnon", "Active(anon)" },
884 { "InactiveAnon", "Inactive(anon)" },
885 { "ActiveFile" , "Active(file)" },
886 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800887 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700888 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800889 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
890 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700891 // { "Dirty", "Dirty" },
892 // { "Writeback", "Writeback" },
893 { "AnonPages", "AnonPages" },
894 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800895 { "Shmem", "Shmem", kMeminfoOp_HistLog },
896 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700897 // { "SReclaimable", "SReclaimable" },
898 // { "SUnreclaim", "SUnreclaim" },
899 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700900 vector<MeminfoRecord> fields(fields_array,
901 fields_array + arraysize(fields_array));
902 if (!FillMeminfo(meminfo_raw, &fields)) {
903 return false;
904 }
905 int total_memory = fields[0].value;
906 if (total_memory == 0) {
907 // this "cannot happen"
908 LOG(WARNING) << "borked meminfo parser";
909 return false;
910 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800911 int swap_total = 0;
912 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700913 // Send all fields retrieved, except total memory.
914 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800915 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
916 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800917 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800918 switch (fields[i].op) {
919 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800920 // report value as percent of total memory
921 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800922 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800923 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800924 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800925 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800926 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800927 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800928 case kMeminfoOp_SwapTotal:
929 swap_total = fields[i].value;
930 case kMeminfoOp_SwapFree:
931 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800932 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700933 }
934 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800935 if (swap_total > 0) {
936 int swap_used = swap_total - swap_free;
937 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800938 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
939 SendLinearSample("Platform.MeminfoSwapUsedPercent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800940 100, 101);
941 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700942 return true;
943}
944
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700945bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
946 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700947 vector<string> lines;
948 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700949
950 // Scan meminfo output and collect field values. Each field name has to
951 // match a meminfo entry (case insensitive) after removing non-alpha
952 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700953 unsigned int ifield = 0;
954 for (unsigned int iline = 0;
955 iline < nlines && ifield < fields->size();
956 iline++) {
957 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700958 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700959 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
960 // Name matches. Parse value and save.
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700961 char* rest;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700962 (*fields)[ifield].value =
963 static_cast<int>(strtol(tokens[1].c_str(), &rest, 10));
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700964 if (*rest != '\0') {
965 LOG(WARNING) << "missing meminfo value";
966 return false;
967 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700968 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700969 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700970 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700971 if (ifield < fields->size()) {
972 // End of input reached while scanning.
973 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
974 << " and following";
975 return false;
976 }
977 return true;
978}
979
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800980void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700981 if (testing_) {
982 return;
983 }
Steve Funge86591e2014-12-01 13:38:21 -0800984 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
985 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
986 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700987}
988
989void MetricsDaemon::MemuseCallback() {
990 // Since we only care about active time (i.e. uptime minus sleep time) but
991 // the callbacks are driven by real time (uptime), we check if we should
992 // reschedule this callback due to intervening sleep periods.
993 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800994 // Avoid intervals of less than one second.
995 double remaining_time = ceil(memuse_final_time_ - now);
996 if (remaining_time > 0) {
997 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700998 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800999 // Report stats and advance the measurement interval unless there are
1000 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -07001001 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001002 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
1003 double interval = kMemuseIntervals[memuse_interval_index_++];
1004 memuse_final_time_ = now + interval;
1005 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001006 }
1007 }
1008}
1009
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001010bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001011 string meminfo_raw;
1012 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -08001013 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001014 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
1015 return false;
1016 }
1017 return ProcessMemuse(meminfo_raw);
1018}
1019
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001020bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001021 static const MeminfoRecord fields_array[] = {
1022 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
1023 { "ActiveAnon", "Active(anon)" },
1024 { "InactiveAnon", "Inactive(anon)" },
1025 };
1026 vector<MeminfoRecord> fields(fields_array,
1027 fields_array + arraysize(fields_array));
1028 if (!FillMeminfo(meminfo_raw, &fields)) {
1029 return false;
1030 }
1031 int total = fields[0].value;
1032 int active_anon = fields[1].value;
1033 int inactive_anon = fields[2].value;
1034 if (total == 0) {
1035 // this "cannot happen"
1036 LOG(WARNING) << "borked meminfo parser";
1037 return false;
1038 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -08001039 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
1040 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001041 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -07001042 100, 101);
1043 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001044}
1045
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001046void MetricsDaemon::ReportDailyUse(int use_seconds) {
1047 if (use_seconds <= 0)
Darin Petkov1bb904e2010-06-16 15:58:06 -07001048 return;
1049
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001050 int minutes = (use_seconds + kSecondsPerMinute / 2) / kSecondsPerMinute;
1051 SendSample("Logging.DailyUseTime",
1052 minutes,
1053 1,
1054 kMinutesPerDay * 30 * 2, // cumulative---two months worth
1055 50);
Darin Petkovf1e85e42010-06-10 15:59:53 -07001056}
1057
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001058void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -07001059 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -07001060 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -07001061}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001062
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001063void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001064 // Report the number of crashes for this OS version, but don't clear the
1065 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -07001066 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001067 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001068 crashes_count,
1069 1, // value of first bucket
1070 500, // value of last bucket
1071 100); // number of buckets
1072
1073
Ben Chanf05ab402014-08-07 00:54:59 -07001074 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001075 SendSample(version_cumulative_cpu_use_->Name(),
1076 cpu_use_ms / 1000, // stat is in seconds
1077 1, // device may be used very little...
1078 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
1079 100);
1080
1081 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
1082 // can be zero. Avoid division by zero.
1083 if (cpu_use_ms > 0) {
1084 // Send the crash frequency since update in number of crashes per CPU year.
1085 SendSample("Logging.KernelCrashesPerCpuYear",
1086 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
1087 1,
1088 1000 * 1000, // about one crash every 30s of CPU time
1089 100);
1090 }
1091
Ben Chanf05ab402014-08-07 00:54:59 -07001092 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001093 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001094 SendSample(version_cumulative_active_use_->Name(),
1095 active_use_seconds / 1000, // stat is in seconds
1096 1, // device may be used very little...
1097 8 * 1000 * 1000, // ... or a lot (about 90 days)
1098 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001099 // Same as above, but per year of active time.
1100 SendSample("Logging.KernelCrashesPerActiveYear",
1101 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
1102 1,
1103 1000 * 1000, // about one crash every 30s of active time
1104 100);
1105 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001106}
1107
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001108void MetricsDaemon::SendDailyUseSample(
1109 const scoped_ptr<PersistentInteger>& use) {
1110 SendSample(use->Name(),
1111 use->GetAndClear(),
1112 1, // value of first bucket
1113 kSecondsPerDay, // value of last bucket
1114 50); // number of buckets
1115}
1116
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001117void MetricsDaemon::SendCrashIntervalSample(
1118 const scoped_ptr<PersistentInteger>& interval) {
1119 SendSample(interval->Name(),
1120 interval->GetAndClear(),
1121 1, // value of first bucket
1122 4 * kSecondsPerWeek, // value of last bucket
1123 50); // number of buckets
1124}
1125
1126void MetricsDaemon::SendCrashFrequencySample(
1127 const scoped_ptr<PersistentInteger>& frequency) {
1128 SendSample(frequency->Name(),
1129 frequency->GetAndClear(),
1130 1, // value of first bucket
1131 100, // value of last bucket
1132 50); // number of buckets
1133}
1134
1135void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001136 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001137 // TODO(semenzato): add a proper linear histogram to the Chrome external
1138 // metrics API.
1139 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1140 metrics_lib_->SendEnumToUMA(name, sample, max);
1141}
Daniel Eratc83975a2014-04-04 08:53:44 -07001142
1143void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
1144 Time now_wall_time) {
1145 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001146 daily_active_use_->Add(elapsed_seconds);
1147 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -07001148 user_crash_interval_->Add(elapsed_seconds);
1149 kernel_crash_interval_->Add(elapsed_seconds);
1150 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
1151 last_update_stats_time_ = now_ticks;
1152
1153 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
1154 const int day = since_epoch.InDays();
1155 const int week = day / 7;
1156
1157 if (daily_cycle_->Get() != day) {
1158 daily_cycle_->Set(day);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001159 SendDailyUseSample(daily_active_use_);
1160 SendDailyUseSample(version_cumulative_active_use_);
Daniel Eratc83975a2014-04-04 08:53:44 -07001161 SendCrashFrequencySample(any_crashes_daily_count_);
1162 SendCrashFrequencySample(user_crashes_daily_count_);
1163 SendCrashFrequencySample(kernel_crashes_daily_count_);
1164 SendCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001165 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -07001166 }
1167
1168 if (weekly_cycle_->Get() != week) {
1169 weekly_cycle_->Set(week);
1170 SendCrashFrequencySample(any_crashes_weekly_count_);
1171 SendCrashFrequencySample(user_crashes_weekly_count_);
1172 SendCrashFrequencySample(kernel_crashes_weekly_count_);
1173 SendCrashFrequencySample(unclean_shutdowns_weekly_count_);
1174 }
1175}
1176
Steve Funge86591e2014-12-01 13:38:21 -08001177void MetricsDaemon::HandleUpdateStatsTimeout() {
1178 UpdateStats(TimeTicks::Now(), Time::Now());
1179 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
1180 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
1181 base::Unretained(this)),
1182 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -07001183}