blob: b9d8cf0c4a2f789080018649bd4de5348e47f0c9 [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.
424 SendCrashFrequencySample(any_crashes_daily_count_);
425 SendCrashFrequencySample(user_crashes_daily_count_);
426 SendCrashFrequencySample(kernel_crashes_daily_count_);
427 SendCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700428 SendKernelCrashesCumulativeCountStats(active_use_seconds);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800429
430 if (weekly_cycle_->Get() == week) {
431 // We did this week already.
432 return;
433 }
434 weekly_cycle_->Set(week);
435
436 // Weekly stats.
437 SendCrashFrequencySample(any_crashes_weekly_count_);
438 SendCrashFrequencySample(user_crashes_weekly_count_);
439 SendCrashFrequencySample(kernel_crashes_weekly_count_);
440 SendCrashFrequencySample(unclean_shutdowns_weekly_count_);
441}
442
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700443// One might argue that parts of this should go into
444// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
445
446TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
447
448 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
449 std::string proc_stat_string;
450 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
451 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
452 return TimeDelta();
453 }
454
455 std::vector<std::string> proc_stat_lines;
456 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
457 if (proc_stat_lines.empty()) {
458 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
459 << ": " << proc_stat_string;
460 return TimeDelta();
461 }
462 std::vector<std::string> proc_stat_totals;
463 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
464
465 uint64 user_ticks, user_nice_ticks, system_ticks;
466 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
467 proc_stat_totals[0] != "cpu" ||
468 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
469 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
470 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
471 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
472 return TimeDelta(base::TimeDelta::FromSeconds(0));
473 }
474
475 uint64 total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
476
477 // Sanity check.
478 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
479 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
480 << " to " << total_cpu_use_ticks;
481 return TimeDelta();
482 }
483
484 uint64 diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
485 latest_cpu_use_ticks_ = total_cpu_use_ticks;
486 // Use microseconds to avoid significant truncations.
487 return base::TimeDelta::FromMicroseconds(
488 diff * 1000 * 1000 / ticks_per_second_);
489}
490
Darin Petkovf27f0362010-06-04 13:14:19 -0700491void MetricsDaemon::SetUserActiveState(bool active, Time now) {
Darin Petkov41e06232010-05-03 16:45:37 -0700492 DLOG(INFO) << "user: " << (active ? "active" : "inactive");
493
494 // Calculates the seconds of active use since the last update and
Darin Petkovf27f0362010-06-04 13:14:19 -0700495 // the day since Epoch, and logs the usage data. Guards against the
496 // time jumping back and forth due to the user changing it by
497 // discarding the new use time.
498 int seconds = 0;
499 if (user_active_ && now > user_active_last_) {
500 TimeDelta since_active = now - user_active_last_;
501 if (since_active < TimeDelta::FromSeconds(
502 kUseMonitorIntervalMax + kSecondsPerMinute)) {
503 seconds = static_cast<int>(since_active.InSeconds());
504 }
505 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800506 daily_use_->Add(seconds);
507 user_crash_interval_->Add(seconds);
508 kernel_crash_interval_->Add(seconds);
Darin Petkov41e06232010-05-03 16:45:37 -0700509
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700510 // Updates the CPU time accumulator.
511 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
512
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800513 // Report daily and weekly stats as needed.
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700514 ReportStats(daily_use_->Get(), now);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700515
Darin Petkov41e06232010-05-03 16:45:37 -0700516 // Schedules a use monitor on inactive->active transitions and
517 // unschedules it on active->inactive transitions.
518 if (!user_active_ && active)
519 ScheduleUseMonitor(kUseMonitorIntervalInit, /* backoff */ false);
520 else if (user_active_ && !active)
521 UnscheduleUseMonitor();
522
523 // Remembers the current active state and the time of the last
524 // activity update.
525 user_active_ = active;
526 user_active_last_ = now;
527}
528
Darin Petkov1bb904e2010-06-16 15:58:06 -0700529void MetricsDaemon::ProcessUserCrash() {
530 // Counts the active use time up to now.
531 SetUserActiveState(user_active_, Time::Now());
532
533 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800534 SendCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700535
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800536 any_crashes_daily_count_->Add(1);
537 any_crashes_weekly_count_->Add(1);
538 user_crashes_daily_count_->Add(1);
539 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700540}
541
Darin Petkov38d5cb02010-06-24 12:10:26 -0700542void MetricsDaemon::ProcessKernelCrash() {
543 // Counts the active use time up to now.
544 SetUserActiveState(user_active_, Time::Now());
545
546 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800547 SendCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700548
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800549 any_crashes_daily_count_->Add(1);
550 any_crashes_weekly_count_->Add(1);
551 kernel_crashes_daily_count_->Add(1);
552 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800553
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800554 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700555}
556
Ken Mixterccd84c02010-08-16 19:57:13 -0700557void MetricsDaemon::ProcessUncleanShutdown() {
558 // Counts the active use time up to now.
559 SetUserActiveState(user_active_, Time::Now());
560
561 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800562 SendCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700563
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800564 unclean_shutdowns_daily_count_->Add(1);
565 unclean_shutdowns_weekly_count_->Add(1);
566 any_crashes_daily_count_->Add(1);
567 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700568}
569
Luigi Semenzato8accd332011-05-17 16:37:18 -0700570bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700571 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800572 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700573 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700574
575 // Deletes the crash-detected file so that the daemon doesn't report
576 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800577 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700578 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700579}
580
Darin Petkov41e06232010-05-03 16:45:37 -0700581// static
582gboolean MetricsDaemon::UseMonitorStatic(gpointer data) {
583 return static_cast<MetricsDaemon*>(data)->UseMonitor() ? TRUE : FALSE;
584}
585
586bool MetricsDaemon::UseMonitor() {
Darin Petkovf27f0362010-06-04 13:14:19 -0700587 SetUserActiveState(user_active_, Time::Now());
Darin Petkov41e06232010-05-03 16:45:37 -0700588
589 // If a new monitor source/instance is scheduled, returns false to
590 // tell GLib to destroy this monitor source/instance. Returns true
591 // otherwise to keep calling back this monitor.
592 return !ScheduleUseMonitor(usemon_interval_ * 2, /* backoff */ true);
593}
594
595bool MetricsDaemon::ScheduleUseMonitor(int interval, bool backoff)
596{
Darin Petkov2ccef012010-05-05 16:06:37 -0700597 if (testing_)
598 return false;
599
Darin Petkov41e06232010-05-03 16:45:37 -0700600 // Caps the interval -- the bigger the interval, the more active use
601 // time will be potentially dropped on system shutdown.
602 if (interval > kUseMonitorIntervalMax)
603 interval = kUseMonitorIntervalMax;
604
605 if (backoff) {
606 // Back-off mode is used by the use monitor to reschedule itself
607 // with exponential back-off in time. This mode doesn't create a
608 // new timeout source if the new interval is the same as the old
609 // one. Also, if a new timeout source is created, the old one is
610 // not destroyed explicitly here -- it will be destroyed by GLib
611 // when the monitor returns FALSE (see UseMonitor and
612 // UseMonitorStatic).
613 if (interval == usemon_interval_)
614 return false;
615 } else {
616 UnscheduleUseMonitor();
617 }
618
619 // Schedules a new use monitor for |interval| seconds from now.
620 DLOG(INFO) << "scheduling use monitor in " << interval << " seconds";
621 usemon_source_ = g_timeout_source_new_seconds(interval);
622 g_source_set_callback(usemon_source_, UseMonitorStatic, this,
623 NULL); // No destroy notification.
624 g_source_attach(usemon_source_,
625 NULL); // Default context.
626 usemon_interval_ = interval;
627 return true;
628}
629
630void MetricsDaemon::UnscheduleUseMonitor() {
631 // If there's a use monitor scheduled already, destroys it.
632 if (usemon_source_ == NULL)
633 return;
634
635 DLOG(INFO) << "destroying use monitor";
636 g_source_destroy(usemon_source_);
637 usemon_source_ = NULL;
638 usemon_interval_ = 0;
639}
640
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700641void MetricsDaemon::StatsReporterInit() {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800642 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700643 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800644 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700645 stats_state_ = kStatsLong;
646 stats_initial_time_ = GetActiveTime();
647 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700648 LOG(WARNING) << "not collecting disk stats";
649 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700650 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700651 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800652}
653
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700654void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800655 if (testing_) {
656 return;
657 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700658 g_timeout_add_seconds(wait, StatsCallbackStatic, this);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800659}
660
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700661bool MetricsDaemon::DiskStatsReadStats(long int* read_sectors,
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800662 long int* write_sectors) {
663 int nchars;
664 int nitems;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700665 bool success = false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800666 char line[200];
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700667 if (diskstats_path_.empty()) {
668 return false;
669 }
Luigi Semenzato0f132bb2011-02-28 11:17:43 -0800670 int file = HANDLE_EINTR(open(diskstats_path_.c_str(), O_RDONLY));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800671 if (file < 0) {
672 PLOG(WARNING) << "cannot open " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700673 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800674 }
675 nchars = HANDLE_EINTR(read(file, line, sizeof(line)));
676 if (nchars < 0) {
677 PLOG(WARNING) << "cannot read from " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700678 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800679 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700680 LOG_IF(WARNING, nchars == sizeof(line))
681 << "line too long in " << diskstats_path_;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800682 line[nchars] = '\0';
683 nitems = sscanf(line, "%*d %*d %ld %*d %*d %*d %ld",
684 read_sectors, write_sectors);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700685 if (nitems == 2) {
686 success = true;
687 } else {
688 LOG(WARNING) << "found " << nitems << " items in "
689 << diskstats_path_ << ", expected 2";
690 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800691 }
692 HANDLE_EINTR(close(file));
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700693 return success;
694}
695
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700696bool MetricsDaemon::VmStatsParseStats(const char* stats,
697 struct VmstatRecord* record) {
698 // a mapping of string name to field in VmstatRecord and whether we found it
699 struct mapping {
700 const string name;
701 uint64_t* value_p;
702 bool found;
703 } map[] =
704 { { .name = "pgmajfault",
705 .value_p = &record->page_faults_,
706 .found = false },
707 { .name = "pswpin",
708 .value_p = &record->swap_in_,
709 .found = false },
710 { .name = "pswpout",
711 .value_p = &record->swap_out_,
712 .found = false }, };
713
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700714 // Each line in the file has the form
715 // <ID> <VALUE>
716 // for instance:
717 // nr_free_pages 213427
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700718 vector<string> lines;
719 Tokenize(stats, "\n", &lines);
720 for (vector<string>::iterator it = lines.begin();
721 it != lines.end(); ++it) {
722 vector<string> tokens;
723 base::SplitString(*it, ' ', &tokens);
724 if (tokens.size() == 2) {
725 for (unsigned int i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
726 if (!tokens[0].compare(map[i].name)) {
727 if (!base::StringToUint64(tokens[1], map[i].value_p))
728 return false;
729 map[i].found = true;
730 }
731 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700732 } else {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700733 LOG(WARNING) << "unexpected vmstat format";
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700734 }
735 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700736 // make sure we got all the stats
737 for (unsigned i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
738 if (map[i].found == false) {
739 LOG(WARNING) << "vmstat missing " << map[i].name;
740 return false;
741 }
742 }
743 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700744}
745
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700746bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
747 string value_string;
748 FilePath* path = new FilePath(vmstats_path_);
Ben Chan2e6543d2014-02-05 23:26:25 -0800749 if (!base::ReadFileToString(*path, &value_string)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700750 delete path;
751 LOG(WARNING) << "cannot read " << vmstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700752 return false;
753 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700754 delete path;
755 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800756}
757
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700758bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700759 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700760 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800761 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700762 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
763 return false;
764 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800765 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700766 LOG(WARNING) << "no newline in " << value_string;
767 // Continue even though the lack of newline is suspicious.
768 }
769 if (!base::StringToInt(value_string, value)) {
770 LOG(WARNING) << "cannot convert " << value_string << " to int";
771 return false;
772 }
773 return true;
774}
775
776void MetricsDaemon::SendCpuThrottleMetrics() {
777 // |max_freq| is 0 only the first time through.
778 static int max_freq = 0;
779 if (max_freq == -1)
780 // Give up, as sysfs did not report max_freq correctly.
781 return;
782 if (max_freq == 0 || testing_) {
783 // One-time initialization of max_freq. (Every time when testing.)
784 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
785 max_freq = -1;
786 return;
787 }
788 if (max_freq == 0) {
789 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
790 max_freq = -1;
791 return;
792 }
793 if (max_freq % 10000 == 1000) {
794 // Special case: system has turbo mode, and max non-turbo frequency is
795 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
796 // being multiples of (at least) 10 MHz. Although there is no guarantee
797 // of this, it seems a fairly reasonable assumption. Otherwise we should
798 // read scaling_available_frequencies, sort the frequencies, compare the
799 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
800 // hack too, no telling when it will change).
801 max_freq -= 1000;
802 }
803 }
804 int scaled_freq = 0;
805 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
806 return;
807 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
808 // scaled_freq is not the actual turbo frequency. We indicate this situation
809 // with a 101% value.
810 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800811 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700812}
813
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800814// static
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700815gboolean MetricsDaemon::StatsCallbackStatic(void* handle) {
816 (static_cast<MetricsDaemon*>(handle))->StatsCallback();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800817 return false; // one-time callback
818}
819
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700820// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700821
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700822void MetricsDaemon::StatsCallback() {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700823 long int read_sectors_now, write_sectors_now;
824 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700825 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700826 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700827 if (testing_) {
828 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700829 delta_time = stats_state_ == kStatsShort ?
830 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700831 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700832 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
833 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700834 int delta_read = read_sectors_now - read_sectors_;
835 int delta_write = write_sectors_now - write_sectors_;
836 int read_sectors_per_second = delta_read / delta_time;
837 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700838 bool vmstats_success = VmStatsReadStats(&vmstats_now);
839 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
840 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
841 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
842 uint64_t page_faults_per_second = delta_faults / delta_time;
843 uint64_t swap_in_per_second = delta_swap_in / delta_time;
844 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800845
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700846 switch (stats_state_) {
847 case kStatsShort:
848 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800849 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700850 read_sectors_per_second,
851 1,
852 kMetricSectorsIOMax,
853 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800854 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700855 write_sectors_per_second,
856 1,
857 kMetricSectorsIOMax,
858 kMetricSectorsBuckets);
859 }
860 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800861 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700862 page_faults_per_second,
863 1,
864 kMetricPageFaultsMax,
865 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800866 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700867 swap_in_per_second,
868 1,
869 kMetricPageFaultsMax,
870 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800871 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700872 swap_out_per_second,
873 1,
874 kMetricPageFaultsMax,
875 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700876 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800877 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700878 stats_state_ = kStatsLong;
879 ScheduleStatsCallback(kMetricStatsLongInterval -
880 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800881 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700882 case kStatsLong:
883 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800884 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700885 read_sectors_per_second,
886 1,
887 kMetricSectorsIOMax,
888 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800889 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700890 write_sectors_per_second,
891 1,
892 kMetricSectorsIOMax,
893 kMetricSectorsBuckets);
894 // Reset sector counters.
895 read_sectors_ = read_sectors_now;
896 write_sectors_ = write_sectors_now;
897 }
898 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800899 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700900 page_faults_per_second,
901 1,
902 kMetricPageFaultsMax,
903 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800904 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700905 swap_in_per_second,
906 1,
907 kMetricPageFaultsMax,
908 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800909 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700910 swap_out_per_second,
911 1,
912 kMetricPageFaultsMax,
913 kMetricPageFaultsBuckets);
914
915 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700916 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700917 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700918 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700919 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800920 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700921 stats_state_ = kStatsShort;
922 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800923 break;
924 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700925 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800926 }
927}
928
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700929void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
930 if (testing_) {
931 return;
932 }
933 g_timeout_add_seconds(wait, MeminfoCallbackStatic, this);
934}
935
936// static
937gboolean MetricsDaemon::MeminfoCallbackStatic(void* handle) {
938 return (static_cast<MetricsDaemon*>(handle))->MeminfoCallback();
939}
940
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700941bool MetricsDaemon::MeminfoCallback() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700942 string meminfo_raw;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700943 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800944 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700945 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
946 return false;
947 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700948 return ProcessMeminfo(meminfo_raw);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700949}
950
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700951bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700952 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700953 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
954 { "MemFree", "MemFree" },
955 { "Buffers", "Buffers" },
956 { "Cached", "Cached" },
957 // { "SwapCached", "SwapCached" },
958 { "Active", "Active" },
959 { "Inactive", "Inactive" },
960 { "ActiveAnon", "Active(anon)" },
961 { "InactiveAnon", "Inactive(anon)" },
962 { "ActiveFile" , "Active(file)" },
963 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800964 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700965 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800966 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
967 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700968 // { "Dirty", "Dirty" },
969 // { "Writeback", "Writeback" },
970 { "AnonPages", "AnonPages" },
971 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800972 { "Shmem", "Shmem", kMeminfoOp_HistLog },
973 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700974 // { "SReclaimable", "SReclaimable" },
975 // { "SUnreclaim", "SUnreclaim" },
976 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700977 vector<MeminfoRecord> fields(fields_array,
978 fields_array + arraysize(fields_array));
979 if (!FillMeminfo(meminfo_raw, &fields)) {
980 return false;
981 }
982 int total_memory = fields[0].value;
983 if (total_memory == 0) {
984 // this "cannot happen"
985 LOG(WARNING) << "borked meminfo parser";
986 return false;
987 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800988 int swap_total = 0;
989 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700990 // Send all fields retrieved, except total memory.
991 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800992 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
993 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800994 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800995 switch (fields[i].op) {
996 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800997 // report value as percent of total memory
998 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800999 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -08001000 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -08001001 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -08001002 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001003 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -08001004 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -08001005 case kMeminfoOp_SwapTotal:
1006 swap_total = fields[i].value;
1007 case kMeminfoOp_SwapFree:
1008 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -08001009 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -07001010 }
1011 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -08001012 if (swap_total > 0) {
1013 int swap_used = swap_total - swap_free;
1014 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001015 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
1016 SendLinearSample("Platform.MeminfoSwapUsedPercent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -08001017 100, 101);
1018 }
Luigi Semenzato8accd332011-05-17 16:37:18 -07001019 return true;
1020}
1021
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001022bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
1023 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001024 vector<string> lines;
1025 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001026
1027 // Scan meminfo output and collect field values. Each field name has to
1028 // match a meminfo entry (case insensitive) after removing non-alpha
1029 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -07001030 unsigned int ifield = 0;
1031 for (unsigned int iline = 0;
1032 iline < nlines && ifield < fields->size();
1033 iline++) {
1034 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001035 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001036 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
1037 // Name matches. Parse value and save.
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001038 char* rest;
Luigi Semenzato8accd332011-05-17 16:37:18 -07001039 (*fields)[ifield].value =
1040 static_cast<int>(strtol(tokens[1].c_str(), &rest, 10));
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001041 if (*rest != '\0') {
1042 LOG(WARNING) << "missing meminfo value";
1043 return false;
1044 }
Luigi Semenzato8accd332011-05-17 16:37:18 -07001045 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001046 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001047 }
Luigi Semenzato8accd332011-05-17 16:37:18 -07001048 if (ifield < fields->size()) {
1049 // End of input reached while scanning.
1050 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
1051 << " and following";
1052 return false;
1053 }
1054 return true;
1055}
1056
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001057void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001058 if (testing_) {
1059 return;
1060 }
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001061 g_timeout_add_seconds(interval, MemuseCallbackStatic, this);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001062}
1063
1064// static
1065gboolean MetricsDaemon::MemuseCallbackStatic(void* handle) {
1066 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(handle);
1067 daemon->MemuseCallback();
1068 return false;
1069}
1070
1071void MetricsDaemon::MemuseCallback() {
1072 // Since we only care about active time (i.e. uptime minus sleep time) but
1073 // the callbacks are driven by real time (uptime), we check if we should
1074 // reschedule this callback due to intervening sleep periods.
1075 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001076 // Avoid intervals of less than one second.
1077 double remaining_time = ceil(memuse_final_time_ - now);
1078 if (remaining_time > 0) {
1079 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001080 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001081 // Report stats and advance the measurement interval unless there are
1082 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -07001083 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -08001084 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
1085 double interval = kMemuseIntervals[memuse_interval_index_++];
1086 memuse_final_time_ = now + interval;
1087 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -07001088 }
1089 }
1090}
1091
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001092bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001093 string meminfo_raw;
1094 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -08001095 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001096 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
1097 return false;
1098 }
1099 return ProcessMemuse(meminfo_raw);
1100}
1101
Luigi Semenzato5bd764f2011-10-14 12:03:35 -07001102bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -07001103 static const MeminfoRecord fields_array[] = {
1104 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
1105 { "ActiveAnon", "Active(anon)" },
1106 { "InactiveAnon", "Inactive(anon)" },
1107 };
1108 vector<MeminfoRecord> fields(fields_array,
1109 fields_array + arraysize(fields_array));
1110 if (!FillMeminfo(meminfo_raw, &fields)) {
1111 return false;
1112 }
1113 int total = fields[0].value;
1114 int active_anon = fields[1].value;
1115 int inactive_anon = fields[2].value;
1116 if (total == 0) {
1117 // this "cannot happen"
1118 LOG(WARNING) << "borked meminfo parser";
1119 return false;
1120 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -08001121 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
1122 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001123 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -07001124 100, 101);
1125 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001126}
1127
Darin Petkovf1e85e42010-06-10 15:59:53 -07001128// static
Luigi Semenzato859b3f02014-02-05 15:33:19 -08001129void MetricsDaemon::ReportDailyUse(void* handle, int count) {
Darin Petkov1bb904e2010-06-16 15:58:06 -07001130 if (count <= 0)
1131 return;
1132
Darin Petkovf1e85e42010-06-10 15:59:53 -07001133 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(handle);
1134 int minutes = (count + kSecondsPerMinute / 2) / kSecondsPerMinute;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001135 daemon->SendSample("Logging.DailyUseTime",
1136 minutes,
1137 1,
1138 kMinutesPerDay,
1139 50);
Darin Petkovf1e85e42010-06-10 15:59:53 -07001140}
1141
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001142void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -07001143 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -07001144 DLOG(INFO) << "received metric: " << name << " " << sample << " "
1145 << min << " " << max << " " << nbuckets;
1146 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -07001147}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001148
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001149void MetricsDaemon::SendKernelCrashesCumulativeCountStats(
1150 int64 active_use_seconds) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001151 // Report the number of crashes for this OS version, but don't clear the
1152 // counter. It is cleared elsewhere on version change.
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001153 int64 crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001154 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001155 crashes_count,
1156 1, // value of first bucket
1157 500, // value of last bucket
1158 100); // number of buckets
1159
1160
1161 int64 cpu_use_ms = version_cumulative_cpu_use_->Get();
1162 SendSample(version_cumulative_cpu_use_->Name(),
1163 cpu_use_ms / 1000, // stat is in seconds
1164 1, // device may be used very little...
1165 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
1166 100);
1167
1168 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
1169 // can be zero. Avoid division by zero.
1170 if (cpu_use_ms > 0) {
1171 // Send the crash frequency since update in number of crashes per CPU year.
1172 SendSample("Logging.KernelCrashesPerCpuYear",
1173 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
1174 1,
1175 1000 * 1000, // about one crash every 30s of CPU time
1176 100);
1177 }
1178
1179 if (active_use_seconds > 0) {
1180 // Same as above, but per year of active time.
1181 SendSample("Logging.KernelCrashesPerActiveYear",
1182 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
1183 1,
1184 1000 * 1000, // about one crash every 30s of active time
1185 100);
1186 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001187}
1188
1189void MetricsDaemon::SendCrashIntervalSample(
1190 const scoped_ptr<PersistentInteger>& interval) {
1191 SendSample(interval->Name(),
1192 interval->GetAndClear(),
1193 1, // value of first bucket
1194 4 * kSecondsPerWeek, // value of last bucket
1195 50); // number of buckets
1196}
1197
1198void MetricsDaemon::SendCrashFrequencySample(
1199 const scoped_ptr<PersistentInteger>& frequency) {
1200 SendSample(frequency->Name(),
1201 frequency->GetAndClear(),
1202 1, // value of first bucket
1203 100, // value of last bucket
1204 50); // number of buckets
1205}
1206
1207void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001208 int max, int nbuckets) {
1209 DLOG(INFO) << "received linear metric: " << name << " " << sample << " "
1210 << max << " " << nbuckets;
1211 // TODO(semenzato): add a proper linear histogram to the Chrome external
1212 // metrics API.
1213 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1214 metrics_lib_->SendEnumToUMA(name, sample, max);
1215}