blob: 1f20699ac200f98ff6f82a15f5a85fc567efbc02 [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
5#include "metrics_daemon.h"
Darin Petkov65b01462010-04-14 13:32:20 -07006
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -08007#include <fcntl.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -07008#include <math.h>
Ken Mixter4c5daa42010-08-26 18:35:06 -07009#include <string.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -070010#include <time.h>
Darin Petkov65b01462010-04-14 13:32:20 -070011
Luigi Semenzato859b3f02014-02-05 15:33:19 -080012#include <base/at_exit.h>
Darin Petkov38d5cb02010-06-24 12:10:26 -070013#include <base/file_util.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080014#include <base/files/file_path.h>
15#include <base/hash.h>
Darin Petkov65b01462010-04-14 13:32:20 -070016#include <base/logging.h>
Ben Chan2e6543d2014-02-05 23:26:25 -080017#include <base/strings/string_number_conversions.h>
18#include <base/strings/string_split.h>
19#include <base/strings/string_util.h>
20#include <base/strings/stringprintf.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080021#include <base/sys_info.h>
Darin Petkov40f25732013-04-29 15:07:31 +020022#include <chromeos/dbus/service_constants.h>
Ken Mixter4c5daa42010-08-26 18:35:06 -070023#include <dbus/dbus-glib-lowlevel.h>
Darin Petkov65b01462010-04-14 13:32:20 -070024
Ben Chan2e6543d2014-02-05 23:26:25 -080025using base::FilePath;
26using base::StringPrintf;
Darin Petkovf27f0362010-06-04 13:14:19 -070027using base::Time;
28using base::TimeDelta;
29using base::TimeTicks;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080030using chromeos_metrics::PersistentInteger;
Luigi Semenzato8accd332011-05-17 16:37:18 -070031using std::map;
Darin Petkov38d5cb02010-06-24 12:10:26 -070032using std::string;
Luigi Semenzato8accd332011-05-17 16:37:18 -070033using std::vector;
34
Darin Petkovf27f0362010-06-04 13:14:19 -070035
Darin Petkov703ec972010-04-27 11:02:18 -070036#define SAFE_MESSAGE(e) (e.message ? e.message : "unknown error")
Darin Petkov40f25732013-04-29 15:07:31 +020037
38static const char kCrashReporterInterface[] = "org.chromium.CrashReporter";
39static const char kCrashReporterUserCrashSignal[] = "UserCrash";
Darin Petkov41e06232010-05-03 16:45:37 -070040
Darin Petkov41e06232010-05-03 16:45:37 -070041static const int kSecondsPerMinute = 60;
42static const int kMinutesPerHour = 60;
43static const int kHoursPerDay = 24;
44static const int kMinutesPerDay = kHoursPerDay * kMinutesPerHour;
Darin Petkov1bb904e2010-06-16 15:58:06 -070045static const int kSecondsPerDay = kSecondsPerMinute * kMinutesPerDay;
46static const int kDaysPerWeek = 7;
47static const int kSecondsPerWeek = kSecondsPerDay * kDaysPerWeek;
Darin Petkov41e06232010-05-03 16:45:37 -070048
49// The daily use monitor is scheduled to a 1-minute interval after
50// initial user activity and then it's exponentially backed off to
51// 10-minute intervals. Although not required, the back off is
52// implemented because the histogram buckets are spaced exponentially
53// anyway and to avoid too frequent metrics daemon process wake-ups
54// and file I/O.
55static const int kUseMonitorIntervalInit = 1 * kSecondsPerMinute;
56static const int kUseMonitorIntervalMax = 10 * kSecondsPerMinute;
Darin Petkov65b01462010-04-14 13:32:20 -070057
Luigi Semenzatoc5a92342014-02-14 15:05:51 -080058const char kKernelCrashDetectedFile[] = "/var/run/kernel-crash-detected";
Ken Mixterccd84c02010-08-16 19:57:13 -070059static const char kUncleanShutdownDetectedFile[] =
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080060 "/var/run/unclean-shutdown-detected";
Ken Mixterccd84c02010-08-16 19:57:13 -070061
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080062// disk stats metrics
63
64// The {Read,Write}Sectors numbers are in sectors/second.
65// A sector is usually 512 bytes.
66
67const char MetricsDaemon::kMetricReadSectorsLongName[] =
68 "Platform.ReadSectorsLong";
69const char MetricsDaemon::kMetricWriteSectorsLongName[] =
70 "Platform.WriteSectorsLong";
71const char MetricsDaemon::kMetricReadSectorsShortName[] =
72 "Platform.ReadSectorsShort";
73const char MetricsDaemon::kMetricWriteSectorsShortName[] =
74 "Platform.WriteSectorsShort";
75
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070076const int MetricsDaemon::kMetricStatsShortInterval = 1; // seconds
77const int MetricsDaemon::kMetricStatsLongInterval = 30; // seconds
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080078
Luigi Semenzato29c7ef92011-04-12 14:12:35 -070079const int MetricsDaemon::kMetricMeminfoInterval = 30; // seconds
80
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080081// Assume a max rate of 250Mb/s for reads (worse for writes) and 512 byte
82// sectors.
83const int MetricsDaemon::kMetricSectorsIOMax = 500000; // sectors/second
84const int MetricsDaemon::kMetricSectorsBuckets = 50; // buckets
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070085// Page size is 4k, sector size is 0.5k. We're not interested in page fault
86// rates that the disk cannot sustain.
87const int MetricsDaemon::kMetricPageFaultsMax = kMetricSectorsIOMax / 8;
88const int MetricsDaemon::kMetricPageFaultsBuckets = 50;
89
90// Major page faults, i.e. the ones that require data to be read from disk.
91
92const char MetricsDaemon::kMetricPageFaultsLongName[] =
93 "Platform.PageFaultsLong";
94const char MetricsDaemon::kMetricPageFaultsShortName[] =
95 "Platform.PageFaultsShort";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080096
Sonny Rao4b8aebb2013-07-31 23:18:31 -070097// Swap in and Swap out
98
99const char MetricsDaemon::kMetricSwapInLongName[] =
100 "Platform.SwapInLong";
101const char MetricsDaemon::kMetricSwapInShortName[] =
102 "Platform.SwapInShort";
103
104const char MetricsDaemon::kMetricSwapOutLongName[] =
105 "Platform.SwapOutLong";
106const char MetricsDaemon::kMetricSwapOutShortName[] =
107 "Platform.SwapOutShort";
108
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700109const char MetricsDaemon::kMetricsProcStatFileName[] = "/proc/stat";
110const int MetricsDaemon::kMetricsProcStatFirstLineItemsCount = 11;
111
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700112// Thermal CPU throttling.
113
114const char MetricsDaemon::kMetricScaledCpuFrequencyName[] =
115 "Platform.CpuFrequencyThermalScaling";
116
Darin Petkov703ec972010-04-27 11:02:18 -0700117// static
Darin Petkov41e06232010-05-03 16:45:37 -0700118const char* MetricsDaemon::kPowerStates_[] = {
Darin Petkov703ec972010-04-27 11:02:18 -0700119#define STATE(name, capname) #name,
120#include "power_states.h"
121};
122
Darin Petkov41e06232010-05-03 16:45:37 -0700123// static
Darin Petkov41e06232010-05-03 16:45:37 -0700124const char* MetricsDaemon::kSessionStates_[] = {
125#define STATE(name, capname) #name,
126#include "session_states.h"
127};
128
Luigi Semenzato8accd332011-05-17 16:37:18 -0700129// Memory use stats collection intervals. We collect some memory use interval
130// at these intervals after boot, and we stop collecting after the last one,
131// with the assumption that in most cases the memory use won't change much
132// after that.
133static const int kMemuseIntervals[] = {
134 1 * kSecondsPerMinute, // 1 minute mark
135 4 * kSecondsPerMinute, // 5 minute mark
136 25 * kSecondsPerMinute, // 0.5 hour mark
137 120 * kSecondsPerMinute, // 2.5 hour mark
138 600 * kSecondsPerMinute, // 12.5 hour mark
139};
140
Darin Petkovf1e85e42010-06-10 15:59:53 -0700141MetricsDaemon::MetricsDaemon()
Sam Leffler239b8262010-08-30 08:56:58 -0700142 : power_state_(kUnknownPowerState),
Darin Petkovf1e85e42010-06-10 15:59:53 -0700143 session_state_(kUnknownSessionState),
144 user_active_(false),
145 usemon_interval_(0),
Luigi Semenzato8accd332011-05-17 16:37:18 -0700146 usemon_source_(NULL),
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800147 memuse_final_time_(0),
Luigi Semenzato8accd332011-05-17 16:37:18 -0700148 memuse_interval_index_(0),
149 read_sectors_(0),
150 write_sectors_(0),
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700151 vmstats_(),
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700152 stats_state_(kStatsShort),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700153 stats_initial_time_(0),
154 ticks_per_second_(0),
155 latest_cpu_use_ticks_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700156
Ken Mixter4c5daa42010-08-26 18:35:06 -0700157MetricsDaemon::~MetricsDaemon() {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700158}
159
Luigi Semenzato8accd332011-05-17 16:37:18 -0700160double MetricsDaemon::GetActiveTime() {
161 struct timespec ts;
162 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
163 if (r < 0) {
164 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
165 return 0;
166 } else {
167 return ts.tv_sec + ((double) ts.tv_nsec) / (1000 * 1000 * 1000);
168 }
169}
170
Darin Petkov2ccef012010-05-05 16:06:37 -0700171void MetricsDaemon::Run(bool run_as_daemon) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800172 base::AtExitManager at_exit_manager;
173
Darin Petkov38d5cb02010-06-24 12:10:26 -0700174 if (run_as_daemon && daemon(0, 0) != 0)
175 return;
176
Ken Mixterccd84c02010-08-16 19:57:13 -0700177 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
178 ProcessKernelCrash();
179 }
180
181 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
182 ProcessUncleanShutdown();
183 }
184
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800185 // On OS version change, clear version stats (which are reported daily).
186 int32 version = GetOsVersionHash();
187 if (version_cycle_->Get() != version) {
188 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800189 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700190 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800191 }
192
Darin Petkov38d5cb02010-06-24 12:10:26 -0700193 Loop();
Darin Petkov65b01462010-04-14 13:32:20 -0700194}
195
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800196uint32 MetricsDaemon::GetOsVersionHash() {
197 static uint32 cached_version_hash = 0;
198 static bool version_hash_is_cached = false;
199 if (version_hash_is_cached)
200 return cached_version_hash;
201 version_hash_is_cached = true;
202 std::string version;
203 if (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_VERSION", &version)) {
204 cached_version_hash = base::Hash(version);
205 } else if (testing_) {
206 cached_version_hash = 42; // return any plausible value for the hash
207 } else {
208 LOG(FATAL) << "could not find CHROMEOS_RELEASE_VERSION";
209 }
210 return cached_version_hash;
211}
212
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800213void MetricsDaemon::Init(bool testing, MetricsLibraryInterface* metrics_lib,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700214 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700215 const string& vmstats_path,
216 const string& scaling_max_freq_path,
217 const string& cpuinfo_max_freq_path
218 ) {
Darin Petkov65b01462010-04-14 13:32:20 -0700219 testing_ = testing;
Darin Petkovfc91b422010-05-12 13:05:45 -0700220 DCHECK(metrics_lib != NULL);
221 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700222
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700223 // Get ticks per second (HZ) on this system.
224 // Sysconf cannot fail, so no sanity checks are needed.
225 ticks_per_second_ = sysconf(_SC_CLK_TCK);
226
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800227 daily_use_.reset(
228 new PersistentInteger("Logging.DailyUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700229 version_cumulative_cpu_use_.reset(
230 new PersistentInteger("Logging.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700231
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800232 kernel_crash_interval_.reset(
233 new PersistentInteger("Logging.KernelCrashInterval"));
234 unclean_shutdown_interval_.reset(
235 new PersistentInteger("Logging.UncleanShutdownInterval"));
236 user_crash_interval_.reset(
237 new PersistentInteger("Logging.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700238
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800239 any_crashes_daily_count_.reset(
240 new PersistentInteger("Logging.AnyCrashesDaily"));
241 any_crashes_weekly_count_.reset(
242 new PersistentInteger("Logging.AnyCrashesWeekly"));
243 user_crashes_daily_count_.reset(
244 new PersistentInteger("Logging.UserCrashesDaily"));
245 user_crashes_weekly_count_.reset(
246 new PersistentInteger("Logging.UserCrashesWeekly"));
247 kernel_crashes_daily_count_.reset(
248 new PersistentInteger("Logging.KernelCrashesDaily"));
249 kernel_crashes_weekly_count_.reset(
250 new PersistentInteger("Logging.KernelCrashesWeekly"));
251 kernel_crashes_version_count_.reset(
252 new PersistentInteger("Logging.KernelCrashesSinceUpdate"));
253 unclean_shutdowns_daily_count_.reset(
254 new PersistentInteger("Logging.UncleanShutdownsDaily"));
255 unclean_shutdowns_weekly_count_.reset(
256 new PersistentInteger("Logging.UncleanShutdownsWeekly"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700257
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800258 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
259 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
260 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800261
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700262 diskstats_path_ = diskstats_path;
263 vmstats_path_ = vmstats_path;
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700264 scaling_max_freq_path_ = scaling_max_freq_path;
265 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700266 StatsReporterInit();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800267
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700268 // Start collecting meminfo stats.
269 ScheduleMeminfoCallback(kMetricMeminfoInterval);
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800270 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
271 ScheduleMemuseCallback(kMemuseIntervals[0]);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700272
Darin Petkov2ccef012010-05-05 16:06:37 -0700273 // Don't setup D-Bus and GLib in test mode.
274 if (testing)
275 return;
Darin Petkov65b01462010-04-14 13:32:20 -0700276
Darin Petkov703ec972010-04-27 11:02:18 -0700277 g_type_init();
Ben Chan6f598422013-06-22 06:29:36 -0700278 dbus_threads_init_default();
Darin Petkov65b01462010-04-14 13:32:20 -0700279
Darin Petkov703ec972010-04-27 11:02:18 -0700280 DBusError error;
281 dbus_error_init(&error);
Darin Petkov65b01462010-04-14 13:32:20 -0700282
David James3b3add52010-06-04 15:01:19 -0700283 DBusConnection* connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
Darin Petkov703ec972010-04-27 11:02:18 -0700284 LOG_IF(FATAL, dbus_error_is_set(&error)) <<
285 "No D-Bus connection: " << SAFE_MESSAGE(error);
Darin Petkov65b01462010-04-14 13:32:20 -0700286
Darin Petkov703ec972010-04-27 11:02:18 -0700287 dbus_connection_setup_with_g_main(connection, NULL);
Darin Petkov65b01462010-04-14 13:32:20 -0700288
Darin Petkov40f25732013-04-29 15:07:31 +0200289 vector<string> matches;
290 matches.push_back(
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800291 base::StringPrintf("type='signal',interface='%s',path='/',member='%s'",
292 kCrashReporterInterface,
293 kCrashReporterUserCrashSignal));
Darin Petkov40f25732013-04-29 15:07:31 +0200294 matches.push_back(
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800295 base::StringPrintf("type='signal',interface='%s',path='%s',member='%s'",
296 power_manager::kPowerManagerInterface,
297 power_manager::kPowerManagerServicePath,
298 power_manager::kPowerStateChangedSignal));
Darin Petkov40f25732013-04-29 15:07:31 +0200299 matches.push_back(
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800300 base::StringPrintf("type='signal',sender='%s',interface='%s',path='%s'",
301 login_manager::kSessionManagerServiceName,
302 login_manager::kSessionManagerInterface,
303 login_manager::kSessionManagerServicePath));
Darin Petkov40f25732013-04-29 15:07:31 +0200304
Darin Petkov703ec972010-04-27 11:02:18 -0700305 // Registers D-Bus matches for the signals we would like to catch.
Darin Petkov40f25732013-04-29 15:07:31 +0200306 for (vector<string>::const_iterator it = matches.begin();
307 it != matches.end(); ++it) {
308 const char* match = it->c_str();
Darin Petkov41e06232010-05-03 16:45:37 -0700309 DLOG(INFO) << "adding dbus match: " << match;
Darin Petkov703ec972010-04-27 11:02:18 -0700310 dbus_bus_add_match(connection, match, &error);
311 LOG_IF(FATAL, dbus_error_is_set(&error)) <<
312 "unable to add a match: " << SAFE_MESSAGE(error);
313 }
314
315 // Adds the D-Bus filter routine to be called back whenever one of
316 // the registered D-Bus matches is successful. The daemon is not
317 // activated for D-Bus messages that don't match.
318 CHECK(dbus_connection_add_filter(connection, MessageFilter, this, NULL));
Darin Petkov65b01462010-04-14 13:32:20 -0700319}
320
321void MetricsDaemon::Loop() {
Darin Petkov703ec972010-04-27 11:02:18 -0700322 GMainLoop* loop = g_main_loop_new(NULL, false);
323 g_main_loop_run(loop);
Darin Petkov65b01462010-04-14 13:32:20 -0700324}
325
Darin Petkov703ec972010-04-27 11:02:18 -0700326// static
327DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
328 DBusMessage* message,
329 void* user_data) {
Darin Petkovf27f0362010-06-04 13:14:19 -0700330 Time now = Time::Now();
Darin Petkovf27f0362010-06-04 13:14:19 -0700331 DLOG(INFO) << "message intercepted @ " << now.ToInternalValue();
Darin Petkov703ec972010-04-27 11:02:18 -0700332
333 int message_type = dbus_message_get_type(message);
334 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700335 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700336 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
337 }
338
339 // Signal messages always have interfaces.
340 const char* interface = dbus_message_get_interface(message);
341 CHECK(interface != NULL);
342
343 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
344
345 DBusMessageIter iter;
346 dbus_message_iter_init(message, &iter);
Darin Petkov40f25732013-04-29 15:07:31 +0200347 if (strcmp(interface, kCrashReporterInterface) == 0) {
Darin Petkov1bb904e2010-06-16 15:58:06 -0700348 CHECK(strcmp(dbus_message_get_member(message),
Darin Petkov40f25732013-04-29 15:07:31 +0200349 kCrashReporterUserCrashSignal) == 0);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700350 daemon->ProcessUserCrash();
Darin Petkov40f25732013-04-29 15:07:31 +0200351 } else if (strcmp(interface, power_manager::kPowerManagerInterface) == 0) {
Darin Petkov41e06232010-05-03 16:45:37 -0700352 CHECK(strcmp(dbus_message_get_member(message),
Darin Petkov40f25732013-04-29 15:07:31 +0200353 power_manager::kPowerStateChangedSignal) == 0);
David James3b3add52010-06-04 15:01:19 -0700354 char* state_name;
Darin Petkov41e06232010-05-03 16:45:37 -0700355 dbus_message_iter_get_basic(&iter, &state_name);
Darin Petkov40f25732013-04-29 15:07:31 +0200356 daemon->PowerStateChanged(state_name, now);
357 } else if (strcmp(interface, login_manager::kSessionManagerInterface) == 0) {
358 const char* member = dbus_message_get_member(message);
359 if (strcmp(member, login_manager::kScreenIsLockedSignal) == 0) {
360 daemon->SetUserActiveState(false, now);
361 } else if (strcmp(member, login_manager::kScreenIsUnlockedSignal) == 0) {
362 daemon->SetUserActiveState(true, now);
363 } else if (strcmp(member, login_manager::kSessionStateChangedSignal) == 0) {
364 char* state_name;
365 dbus_message_iter_get_basic(&iter, &state_name);
366 daemon->SessionStateChanged(state_name, now);
367 }
Darin Petkov703ec972010-04-27 11:02:18 -0700368 } else {
Darin Petkov41e06232010-05-03 16:45:37 -0700369 DLOG(WARNING) << "unexpected interface: " << interface;
Darin Petkov703ec972010-04-27 11:02:18 -0700370 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
371 }
372
373 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700374}
375
Darin Petkovf27f0362010-06-04 13:14:19 -0700376void MetricsDaemon::PowerStateChanged(const char* state_name, Time now) {
Darin Petkov41e06232010-05-03 16:45:37 -0700377 DLOG(INFO) << "power state: " << state_name;
Darin Petkov703ec972010-04-27 11:02:18 -0700378 power_state_ = LookupPowerState(state_name);
Darin Petkov41e06232010-05-03 16:45:37 -0700379
380 if (power_state_ != kPowerStateOn)
381 SetUserActiveState(false, now);
Darin Petkov703ec972010-04-27 11:02:18 -0700382}
383
384MetricsDaemon::PowerState
385MetricsDaemon::LookupPowerState(const char* state_name) {
386 for (int i = 0; i < kNumberPowerStates; i++) {
Darin Petkov41e06232010-05-03 16:45:37 -0700387 if (strcmp(state_name, kPowerStates_[i]) == 0) {
Darin Petkov703ec972010-04-27 11:02:18 -0700388 return static_cast<PowerState>(i);
389 }
390 }
Darin Petkov41e06232010-05-03 16:45:37 -0700391 DLOG(WARNING) << "unknown power state: " << state_name;
Darin Petkov703ec972010-04-27 11:02:18 -0700392 return kUnknownPowerState;
Darin Petkov65b01462010-04-14 13:32:20 -0700393}
394
Darin Petkovf27f0362010-06-04 13:14:19 -0700395void MetricsDaemon::SessionStateChanged(const char* state_name, Time now) {
Darin Petkov41e06232010-05-03 16:45:37 -0700396 DLOG(INFO) << "user session state: " << state_name;
397 session_state_ = LookupSessionState(state_name);
398 SetUserActiveState(session_state_ == kSessionStateStarted, now);
399}
400
401MetricsDaemon::SessionState
402MetricsDaemon::LookupSessionState(const char* state_name) {
403 for (int i = 0; i < kNumberSessionStates; i++) {
404 if (strcmp(state_name, kSessionStates_[i]) == 0) {
405 return static_cast<SessionState>(i);
406 }
407 }
408 DLOG(WARNING) << "unknown user session state: " << state_name;
409 return kUnknownSessionState;
410}
411
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700412void MetricsDaemon::ReportStats(int64 active_use_seconds, Time now) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800413 TimeDelta since_epoch = now - Time::UnixEpoch();
414 int day = since_epoch.InDays();
415 int week = day / 7;
416
417 if (daily_cycle_->Get() == day) {
418 // We did today already.
419 return;
420 }
421 daily_cycle_->Set(day);
422
423 // Daily stats.
Luigi Semenzato5ef2e392014-04-15 15:15:02 -0700424 ReportDailyUse(active_use_seconds);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800425 SendCrashFrequencySample(any_crashes_daily_count_);
426 SendCrashFrequencySample(user_crashes_daily_count_);
427 SendCrashFrequencySample(kernel_crashes_daily_count_);
428 SendCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700429 SendKernelCrashesCumulativeCountStats(active_use_seconds);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800430
431 if (weekly_cycle_->Get() == week) {
432 // We did this week already.
433 return;
434 }
435 weekly_cycle_->Set(week);
436
437 // Weekly stats.
438 SendCrashFrequencySample(any_crashes_weekly_count_);
439 SendCrashFrequencySample(user_crashes_weekly_count_);
440 SendCrashFrequencySample(kernel_crashes_weekly_count_);
441 SendCrashFrequencySample(unclean_shutdowns_weekly_count_);
442}
443
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700444// One might argue that parts of this should go into
445// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
446
447TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
448
449 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
450 std::string proc_stat_string;
451 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
452 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
453 return TimeDelta();
454 }
455
456 std::vector<std::string> proc_stat_lines;
457 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
458 if (proc_stat_lines.empty()) {
459 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
460 << ": " << proc_stat_string;
461 return TimeDelta();
462 }
463 std::vector<std::string> proc_stat_totals;
464 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
465
466 uint64 user_ticks, user_nice_ticks, system_ticks;
467 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
468 proc_stat_totals[0] != "cpu" ||
469 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
470 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
471 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
472 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
473 return TimeDelta(base::TimeDelta::FromSeconds(0));
474 }
475
476 uint64 total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
477
478 // Sanity check.
479 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
480 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
481 << " to " << total_cpu_use_ticks;
482 return TimeDelta();
483 }
484
485 uint64 diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
486 latest_cpu_use_ticks_ = total_cpu_use_ticks;
487 // Use microseconds to avoid significant truncations.
488 return base::TimeDelta::FromMicroseconds(
489 diff * 1000 * 1000 / ticks_per_second_);
490}
491
Darin Petkovf27f0362010-06-04 13:14:19 -0700492void MetricsDaemon::SetUserActiveState(bool active, Time now) {
Darin Petkov41e06232010-05-03 16:45:37 -0700493 DLOG(INFO) << "user: " << (active ? "active" : "inactive");
494
495 // Calculates the seconds of active use since the last update and
Darin Petkovf27f0362010-06-04 13:14:19 -0700496 // the day since Epoch, and logs the usage data. Guards against the
497 // time jumping back and forth due to the user changing it by
498 // discarding the new use time.
499 int seconds = 0;
500 if (user_active_ && now > user_active_last_) {
501 TimeDelta since_active = now - user_active_last_;
502 if (since_active < TimeDelta::FromSeconds(
503 kUseMonitorIntervalMax + kSecondsPerMinute)) {
504 seconds = static_cast<int>(since_active.InSeconds());
505 }
506 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800507 daily_use_->Add(seconds);
508 user_crash_interval_->Add(seconds);
509 kernel_crash_interval_->Add(seconds);
Darin Petkov41e06232010-05-03 16:45:37 -0700510
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700511 // Updates the CPU time accumulator.
512 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
513
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800514 // Report daily and weekly stats as needed.
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700515 ReportStats(daily_use_->Get(), now);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700516
Darin Petkov41e06232010-05-03 16:45:37 -0700517 // Schedules a use monitor on inactive->active transitions and
518 // unschedules it on active->inactive transitions.
519 if (!user_active_ && active)
520 ScheduleUseMonitor(kUseMonitorIntervalInit, /* backoff */ false);
521 else if (user_active_ && !active)
522 UnscheduleUseMonitor();
523
524 // Remembers the current active state and the time of the last
525 // activity update.
526 user_active_ = active;
527 user_active_last_ = now;
528}
529
Darin Petkov1bb904e2010-06-16 15:58:06 -0700530void MetricsDaemon::ProcessUserCrash() {
531 // Counts the active use time up to now.
532 SetUserActiveState(user_active_, Time::Now());
533
534 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800535 SendCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700536
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800537 any_crashes_daily_count_->Add(1);
538 any_crashes_weekly_count_->Add(1);
539 user_crashes_daily_count_->Add(1);
540 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700541}
542
Darin Petkov38d5cb02010-06-24 12:10:26 -0700543void MetricsDaemon::ProcessKernelCrash() {
544 // Counts the active use time up to now.
545 SetUserActiveState(user_active_, Time::Now());
546
547 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800548 SendCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700549
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800550 any_crashes_daily_count_->Add(1);
551 any_crashes_weekly_count_->Add(1);
552 kernel_crashes_daily_count_->Add(1);
553 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800554
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800555 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700556}
557
Ken Mixterccd84c02010-08-16 19:57:13 -0700558void MetricsDaemon::ProcessUncleanShutdown() {
559 // Counts the active use time up to now.
560 SetUserActiveState(user_active_, Time::Now());
561
562 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800563 SendCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700564
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800565 unclean_shutdowns_daily_count_->Add(1);
566 unclean_shutdowns_weekly_count_->Add(1);
567 any_crashes_daily_count_->Add(1);
568 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700569}
570
Luigi Semenzato8accd332011-05-17 16:37:18 -0700571bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700572 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800573 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700574 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700575
576 // Deletes the crash-detected file so that the daemon doesn't report
577 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800578 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700579 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700580}
581
Darin Petkov41e06232010-05-03 16:45:37 -0700582// static
583gboolean MetricsDaemon::UseMonitorStatic(gpointer data) {
584 return static_cast<MetricsDaemon*>(data)->UseMonitor() ? TRUE : FALSE;
585}
586
587bool MetricsDaemon::UseMonitor() {
Darin Petkovf27f0362010-06-04 13:14:19 -0700588 SetUserActiveState(user_active_, Time::Now());
Darin Petkov41e06232010-05-03 16:45:37 -0700589
590 // If a new monitor source/instance is scheduled, returns false to
591 // tell GLib to destroy this monitor source/instance. Returns true
592 // otherwise to keep calling back this monitor.
593 return !ScheduleUseMonitor(usemon_interval_ * 2, /* backoff */ true);
594}
595
596bool MetricsDaemon::ScheduleUseMonitor(int interval, bool backoff)
597{
Darin Petkov2ccef012010-05-05 16:06:37 -0700598 if (testing_)
599 return false;
600
Darin Petkov41e06232010-05-03 16:45:37 -0700601 // Caps the interval -- the bigger the interval, the more active use
602 // time will be potentially dropped on system shutdown.
603 if (interval > kUseMonitorIntervalMax)
604 interval = kUseMonitorIntervalMax;
605
606 if (backoff) {
607 // Back-off mode is used by the use monitor to reschedule itself
608 // with exponential back-off in time. This mode doesn't create a
609 // new timeout source if the new interval is the same as the old
610 // one. Also, if a new timeout source is created, the old one is
611 // not destroyed explicitly here -- it will be destroyed by GLib
612 // when the monitor returns FALSE (see UseMonitor and
613 // UseMonitorStatic).
614 if (interval == usemon_interval_)
615 return false;
616 } else {
617 UnscheduleUseMonitor();
618 }
619
620 // Schedules a new use monitor for |interval| seconds from now.
621 DLOG(INFO) << "scheduling use monitor in " << interval << " seconds";
622 usemon_source_ = g_timeout_source_new_seconds(interval);
623 g_source_set_callback(usemon_source_, UseMonitorStatic, this,
624 NULL); // No destroy notification.
625 g_source_attach(usemon_source_,
626 NULL); // Default context.
627 usemon_interval_ = interval;
628 return true;
629}
630
631void MetricsDaemon::UnscheduleUseMonitor() {
632 // If there's a use monitor scheduled already, destroys it.
633 if (usemon_source_ == NULL)
634 return;
635
636 DLOG(INFO) << "destroying use monitor";
637 g_source_destroy(usemon_source_);
638 usemon_source_ = NULL;
639 usemon_interval_ = 0;
640}
641
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700642void MetricsDaemon::StatsReporterInit() {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800643 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700644 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800645 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700646 stats_state_ = kStatsLong;
647 stats_initial_time_ = GetActiveTime();
648 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700649 LOG(WARNING) << "not collecting disk stats";
650 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700651 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700652 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800653}
654
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700655void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800656 if (testing_) {
657 return;
658 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700659 g_timeout_add_seconds(wait, StatsCallbackStatic, this);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800660}
661
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700662bool MetricsDaemon::DiskStatsReadStats(long int* read_sectors,
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800663 long int* write_sectors) {
664 int nchars;
665 int nitems;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700666 bool success = false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800667 char line[200];
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700668 if (diskstats_path_.empty()) {
669 return false;
670 }
Luigi Semenzato0f132bb2011-02-28 11:17:43 -0800671 int file = HANDLE_EINTR(open(diskstats_path_.c_str(), O_RDONLY));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800672 if (file < 0) {
673 PLOG(WARNING) << "cannot open " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700674 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800675 }
676 nchars = HANDLE_EINTR(read(file, line, sizeof(line)));
677 if (nchars < 0) {
678 PLOG(WARNING) << "cannot read from " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700679 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800680 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700681 LOG_IF(WARNING, nchars == sizeof(line))
682 << "line too long in " << diskstats_path_;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800683 line[nchars] = '\0';
684 nitems = sscanf(line, "%*d %*d %ld %*d %*d %*d %ld",
685 read_sectors, write_sectors);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700686 if (nitems == 2) {
687 success = true;
688 } else {
689 LOG(WARNING) << "found " << nitems << " items in "
690 << diskstats_path_ << ", expected 2";
691 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800692 }
693 HANDLE_EINTR(close(file));
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700694 return success;
695}
696
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700697bool MetricsDaemon::VmStatsParseStats(const char* stats,
698 struct VmstatRecord* record) {
699 // a mapping of string name to field in VmstatRecord and whether we found it
700 struct mapping {
701 const string name;
702 uint64_t* value_p;
703 bool found;
704 } map[] =
705 { { .name = "pgmajfault",
706 .value_p = &record->page_faults_,
707 .found = false },
708 { .name = "pswpin",
709 .value_p = &record->swap_in_,
710 .found = false },
711 { .name = "pswpout",
712 .value_p = &record->swap_out_,
713 .found = false }, };
714
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700715 // Each line in the file has the form
716 // <ID> <VALUE>
717 // for instance:
718 // nr_free_pages 213427
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700719 vector<string> lines;
720 Tokenize(stats, "\n", &lines);
721 for (vector<string>::iterator it = lines.begin();
722 it != lines.end(); ++it) {
723 vector<string> tokens;
724 base::SplitString(*it, ' ', &tokens);
725 if (tokens.size() == 2) {
726 for (unsigned int i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
727 if (!tokens[0].compare(map[i].name)) {
728 if (!base::StringToUint64(tokens[1], map[i].value_p))
729 return false;
730 map[i].found = true;
731 }
732 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700733 } else {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700734 LOG(WARNING) << "unexpected vmstat format";
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700735 }
736 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700737 // make sure we got all the stats
738 for (unsigned i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
739 if (map[i].found == false) {
740 LOG(WARNING) << "vmstat missing " << map[i].name;
741 return false;
742 }
743 }
744 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700745}
746
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700747bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
748 string value_string;
749 FilePath* path = new FilePath(vmstats_path_);
Ben Chan2e6543d2014-02-05 23:26:25 -0800750 if (!base::ReadFileToString(*path, &value_string)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700751 delete path;
752 LOG(WARNING) << "cannot read " << vmstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700753 return false;
754 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700755 delete path;
756 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800757}
758
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700759bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700760 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700761 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800762 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700763 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
764 return false;
765 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800766 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700767 LOG(WARNING) << "no newline in " << value_string;
768 // Continue even though the lack of newline is suspicious.
769 }
770 if (!base::StringToInt(value_string, value)) {
771 LOG(WARNING) << "cannot convert " << value_string << " to int";
772 return false;
773 }
774 return true;
775}
776
777void MetricsDaemon::SendCpuThrottleMetrics() {
778 // |max_freq| is 0 only the first time through.
779 static int max_freq = 0;
780 if (max_freq == -1)
781 // Give up, as sysfs did not report max_freq correctly.
782 return;
783 if (max_freq == 0 || testing_) {
784 // One-time initialization of max_freq. (Every time when testing.)
785 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
786 max_freq = -1;
787 return;
788 }
789 if (max_freq == 0) {
790 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
791 max_freq = -1;
792 return;
793 }
794 if (max_freq % 10000 == 1000) {
795 // Special case: system has turbo mode, and max non-turbo frequency is
796 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
797 // being multiples of (at least) 10 MHz. Although there is no guarantee
798 // of this, it seems a fairly reasonable assumption. Otherwise we should
799 // read scaling_available_frequencies, sort the frequencies, compare the
800 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
801 // hack too, no telling when it will change).
802 max_freq -= 1000;
803 }
804 }
805 int scaled_freq = 0;
806 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
807 return;
808 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
809 // scaled_freq is not the actual turbo frequency. We indicate this situation
810 // with a 101% value.
811 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800812 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700813}
814
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800815// static
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700816gboolean MetricsDaemon::StatsCallbackStatic(void* handle) {
817 (static_cast<MetricsDaemon*>(handle))->StatsCallback();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800818 return false; // one-time callback
819}
820
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700821// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700822
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700823void MetricsDaemon::StatsCallback() {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700824 long int read_sectors_now, write_sectors_now;
825 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700826 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700827 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700828 if (testing_) {
829 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700830 delta_time = stats_state_ == kStatsShort ?
831 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700832 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700833 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
834 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700835 int delta_read = read_sectors_now - read_sectors_;
836 int delta_write = write_sectors_now - write_sectors_;
837 int read_sectors_per_second = delta_read / delta_time;
838 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700839 bool vmstats_success = VmStatsReadStats(&vmstats_now);
840 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
841 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
842 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
843 uint64_t page_faults_per_second = delta_faults / delta_time;
844 uint64_t swap_in_per_second = delta_swap_in / delta_time;
845 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800846
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700847 switch (stats_state_) {
848 case kStatsShort:
849 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800850 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700851 read_sectors_per_second,
852 1,
853 kMetricSectorsIOMax,
854 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800855 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700856 write_sectors_per_second,
857 1,
858 kMetricSectorsIOMax,
859 kMetricSectorsBuckets);
860 }
861 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800862 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700863 page_faults_per_second,
864 1,
865 kMetricPageFaultsMax,
866 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800867 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700868 swap_in_per_second,
869 1,
870 kMetricPageFaultsMax,
871 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800872 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700873 swap_out_per_second,
874 1,
875 kMetricPageFaultsMax,
876 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700877 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800878 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700879 stats_state_ = kStatsLong;
880 ScheduleStatsCallback(kMetricStatsLongInterval -
881 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800882 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700883 case kStatsLong:
884 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800885 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700886 read_sectors_per_second,
887 1,
888 kMetricSectorsIOMax,
889 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800890 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700891 write_sectors_per_second,
892 1,
893 kMetricSectorsIOMax,
894 kMetricSectorsBuckets);
895 // Reset sector counters.
896 read_sectors_ = read_sectors_now;
897 write_sectors_ = write_sectors_now;
898 }
899 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800900 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700901 page_faults_per_second,
902 1,
903 kMetricPageFaultsMax,
904 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800905 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700906 swap_in_per_second,
907 1,
908 kMetricPageFaultsMax,
909 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800910 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700911 swap_out_per_second,
912 1,
913 kMetricPageFaultsMax,
914 kMetricPageFaultsBuckets);
915
916 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700917 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700918 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700919 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700920 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800921 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700922 stats_state_ = kStatsShort;
923 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800924 break;
925 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700926 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800927 }
928}
929
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700930void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
931 if (testing_) {
932 return;
933 }
934 g_timeout_add_seconds(wait, MeminfoCallbackStatic, this);
935}
936
937// static
938gboolean MetricsDaemon::MeminfoCallbackStatic(void* handle) {
939 return (static_cast<MetricsDaemon*>(handle))->MeminfoCallback();
940}
941
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700942bool MetricsDaemon::MeminfoCallback() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700943 string meminfo_raw;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700944 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800945 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700946 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
947 return false;
948 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700949 return ProcessMeminfo(meminfo_raw);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700950}
951
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700952bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700953 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700954 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
955 { "MemFree", "MemFree" },
956 { "Buffers", "Buffers" },
957 { "Cached", "Cached" },
958 // { "SwapCached", "SwapCached" },
959 { "Active", "Active" },
960 { "Inactive", "Inactive" },
961 { "ActiveAnon", "Active(anon)" },
962 { "InactiveAnon", "Inactive(anon)" },
963 { "ActiveFile" , "Active(file)" },
964 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800965 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700966 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800967 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
968 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700969 // { "Dirty", "Dirty" },
970 // { "Writeback", "Writeback" },
971 { "AnonPages", "AnonPages" },
972 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800973 { "Shmem", "Shmem", kMeminfoOp_HistLog },
974 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700975 // { "SReclaimable", "SReclaimable" },
976 // { "SUnreclaim", "SUnreclaim" },
977 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700978 vector<MeminfoRecord> fields(fields_array,
979 fields_array + arraysize(fields_array));
980 if (!FillMeminfo(meminfo_raw, &fields)) {
981 return false;
982 }
983 int total_memory = fields[0].value;
984 if (total_memory == 0) {
985 // this "cannot happen"
986 LOG(WARNING) << "borked meminfo parser";
987 return false;
988 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800989 int swap_total = 0;
990 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700991 // Send all fields retrieved, except total memory.
992 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800993 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
994 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800995 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800996 switch (fields[i].op) {
997 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800998 // report value as percent of total memory
999 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001000 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -08001001 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -08001002 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -08001003 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001004 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -08001005 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -08001006 case kMeminfoOp_SwapTotal:
1007 swap_total = fields[i].value;
1008 case kMeminfoOp_SwapFree:
1009 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -08001010 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -07001011 }
1012 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -08001013 if (swap_total > 0) {
1014 int swap_used = swap_total - swap_free;
1015 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001016 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
1017 SendLinearSample("Platform.MeminfoSwapUsedPercent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -08001018 100, 101);
1019 }
Luigi Semenzato8accd332011-05-17 16:37:18 -07001020 return true;
1021}
1022
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001023bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
1024 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001025 vector<string> lines;
1026 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001027
1028 // Scan meminfo output and collect field values. Each field name has to
1029 // match a meminfo entry (case insensitive) after removing non-alpha
1030 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -07001031 unsigned int ifield = 0;
1032 for (unsigned int iline = 0;
1033 iline < nlines && ifield < fields->size();
1034 iline++) {
1035 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001036 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001037 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
1038 // Name matches. Parse value and save.
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001039 char* rest;
Luigi Semenzato8accd332011-05-17 16:37:18 -07001040 (*fields)[ifield].value =
1041 static_cast<int>(strtol(tokens[1].c_str(), &rest, 10));
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001042 if (*rest != '\0') {
1043 LOG(WARNING) << "missing meminfo value";
1044 return false;
1045 }
Luigi Semenzato8accd332011-05-17 16:37:18 -07001046 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001047 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001048 }
Luigi Semenzato8accd332011-05-17 16:37:18 -07001049 if (ifield < fields->size()) {
1050 // End of input reached while scanning.
1051 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
1052 << " and following";
1053 return false;
1054 }
1055 return true;
1056}
1057
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001058void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001059 if (testing_) {
1060 return;
1061 }
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001062 g_timeout_add_seconds(interval, MemuseCallbackStatic, this);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001063}
1064
1065// static
1066gboolean MetricsDaemon::MemuseCallbackStatic(void* handle) {
1067 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(handle);
1068 daemon->MemuseCallback();
1069 return false;
1070}
1071
1072void MetricsDaemon::MemuseCallback() {
1073 // Since we only care about active time (i.e. uptime minus sleep time) but
1074 // the callbacks are driven by real time (uptime), we check if we should
1075 // reschedule this callback due to intervening sleep periods.
1076 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001077 // Avoid intervals of less than one second.
1078 double remaining_time = ceil(memuse_final_time_ - now);
1079 if (remaining_time > 0) {
1080 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001081 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001082 // Report stats and advance the measurement interval unless there are
1083 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -07001084 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001085 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
1086 double interval = kMemuseIntervals[memuse_interval_index_++];
1087 memuse_final_time_ = now + interval;
1088 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001089 }
1090 }
1091}
1092
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001093bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001094 string meminfo_raw;
1095 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -08001096 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001097 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
1098 return false;
1099 }
1100 return ProcessMemuse(meminfo_raw);
1101}
1102
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001103bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001104 static const MeminfoRecord fields_array[] = {
1105 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
1106 { "ActiveAnon", "Active(anon)" },
1107 { "InactiveAnon", "Inactive(anon)" },
1108 };
1109 vector<MeminfoRecord> fields(fields_array,
1110 fields_array + arraysize(fields_array));
1111 if (!FillMeminfo(meminfo_raw, &fields)) {
1112 return false;
1113 }
1114 int total = fields[0].value;
1115 int active_anon = fields[1].value;
1116 int inactive_anon = fields[2].value;
1117 if (total == 0) {
1118 // this "cannot happen"
1119 LOG(WARNING) << "borked meminfo parser";
1120 return false;
1121 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -08001122 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
1123 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001124 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -07001125 100, 101);
1126 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001127}
1128
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001129void MetricsDaemon::ReportDailyUse(int use_seconds) {
1130 if (use_seconds <= 0)
Darin Petkov1bb904e2010-06-16 15:58:06 -07001131 return;
1132
Luigi Semenzato5ef2e392014-04-15 15:15:02 -07001133 int minutes = (use_seconds + kSecondsPerMinute / 2) / kSecondsPerMinute;
1134 SendSample("Logging.DailyUseTime",
1135 minutes,
1136 1,
1137 kMinutesPerDay * 30 * 2, // cumulative---two months worth
1138 50);
Darin Petkovf1e85e42010-06-10 15:59:53 -07001139}
1140
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001141void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -07001142 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -07001143 DLOG(INFO) << "received metric: " << name << " " << sample << " "
1144 << min << " " << max << " " << nbuckets;
1145 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -07001146}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001147
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001148void MetricsDaemon::SendKernelCrashesCumulativeCountStats(
1149 int64 active_use_seconds) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001150 // Report the number of crashes for this OS version, but don't clear the
1151 // counter. It is cleared elsewhere on version change.
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001152 int64 crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001153 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001154 crashes_count,
1155 1, // value of first bucket
1156 500, // value of last bucket
1157 100); // number of buckets
1158
1159
1160 int64 cpu_use_ms = version_cumulative_cpu_use_->Get();
1161 SendSample(version_cumulative_cpu_use_->Name(),
1162 cpu_use_ms / 1000, // stat is in seconds
1163 1, // device may be used very little...
1164 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
1165 100);
1166
1167 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
1168 // can be zero. Avoid division by zero.
1169 if (cpu_use_ms > 0) {
1170 // Send the crash frequency since update in number of crashes per CPU year.
1171 SendSample("Logging.KernelCrashesPerCpuYear",
1172 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
1173 1,
1174 1000 * 1000, // about one crash every 30s of CPU time
1175 100);
1176 }
1177
1178 if (active_use_seconds > 0) {
1179 // Same as above, but per year of active time.
1180 SendSample("Logging.KernelCrashesPerActiveYear",
1181 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
1182 1,
1183 1000 * 1000, // about one crash every 30s of active time
1184 100);
1185 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001186}
1187
1188void MetricsDaemon::SendCrashIntervalSample(
1189 const scoped_ptr<PersistentInteger>& interval) {
1190 SendSample(interval->Name(),
1191 interval->GetAndClear(),
1192 1, // value of first bucket
1193 4 * kSecondsPerWeek, // value of last bucket
1194 50); // number of buckets
1195}
1196
1197void MetricsDaemon::SendCrashFrequencySample(
1198 const scoped_ptr<PersistentInteger>& frequency) {
1199 SendSample(frequency->Name(),
1200 frequency->GetAndClear(),
1201 1, // value of first bucket
1202 100, // value of last bucket
1203 50); // number of buckets
1204}
1205
1206void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001207 int max, int nbuckets) {
1208 DLOG(INFO) << "received linear metric: " << name << " " << sample << " "
1209 << max << " " << nbuckets;
1210 // TODO(semenzato): add a proper linear histogram to the Chrome external
1211 // metrics API.
1212 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1213 metrics_lib_->SendEnumToUMA(name, sample, max);
1214}