blob: 9b66877a15d63e89ac3b6233588d048b3e30ac13 [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
Daniel Eratc83975a2014-04-04 08:53:44 -070035namespace {
Darin Petkovf27f0362010-06-04 13:14:19 -070036
Darin Petkov703ec972010-04-27 11:02:18 -070037#define SAFE_MESSAGE(e) (e.message ? e.message : "unknown error")
Darin Petkov40f25732013-04-29 15:07:31 +020038
Daniel Eratc83975a2014-04-04 08:53:44 -070039const char kCrashReporterInterface[] = "org.chromium.CrashReporter";
40const char kCrashReporterUserCrashSignal[] = "UserCrash";
Darin Petkov41e06232010-05-03 16:45:37 -070041
Daniel Eratc83975a2014-04-04 08:53:44 -070042const int kSecondsPerMinute = 60;
43const int kMinutesPerHour = 60;
44const int kHoursPerDay = 24;
45const int kMinutesPerDay = kHoursPerDay * kMinutesPerHour;
46const int kSecondsPerDay = kSecondsPerMinute * kMinutesPerDay;
47const int kDaysPerWeek = 7;
48const int kSecondsPerWeek = kSecondsPerDay * kDaysPerWeek;
Darin Petkov41e06232010-05-03 16:45:37 -070049
Daniel Eratc83975a2014-04-04 08:53:44 -070050// Interval between calls to UpdateStats().
51const guint kUpdateStatsIntervalMs = 300000;
Darin Petkov65b01462010-04-14 13:32:20 -070052
Luigi Semenzatoc5a92342014-02-14 15:05:51 -080053const char kKernelCrashDetectedFile[] = "/var/run/kernel-crash-detected";
Daniel Eratc83975a2014-04-04 08:53:44 -070054const char kUncleanShutdownDetectedFile[] =
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080055 "/var/run/unclean-shutdown-detected";
Ken Mixterccd84c02010-08-16 19:57:13 -070056
Daniel Eratc83975a2014-04-04 08:53:44 -070057} // namespace
58
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080059// disk stats metrics
60
61// The {Read,Write}Sectors numbers are in sectors/second.
62// A sector is usually 512 bytes.
63
64const char MetricsDaemon::kMetricReadSectorsLongName[] =
65 "Platform.ReadSectorsLong";
66const char MetricsDaemon::kMetricWriteSectorsLongName[] =
67 "Platform.WriteSectorsLong";
68const char MetricsDaemon::kMetricReadSectorsShortName[] =
69 "Platform.ReadSectorsShort";
70const char MetricsDaemon::kMetricWriteSectorsShortName[] =
71 "Platform.WriteSectorsShort";
72
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070073const int MetricsDaemon::kMetricStatsShortInterval = 1; // seconds
74const int MetricsDaemon::kMetricStatsLongInterval = 30; // seconds
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080075
Luigi Semenzato29c7ef92011-04-12 14:12:35 -070076const int MetricsDaemon::kMetricMeminfoInterval = 30; // seconds
77
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080078// Assume a max rate of 250Mb/s for reads (worse for writes) and 512 byte
79// sectors.
80const int MetricsDaemon::kMetricSectorsIOMax = 500000; // sectors/second
81const int MetricsDaemon::kMetricSectorsBuckets = 50; // buckets
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070082// Page size is 4k, sector size is 0.5k. We're not interested in page fault
83// rates that the disk cannot sustain.
84const int MetricsDaemon::kMetricPageFaultsMax = kMetricSectorsIOMax / 8;
85const int MetricsDaemon::kMetricPageFaultsBuckets = 50;
86
87// Major page faults, i.e. the ones that require data to be read from disk.
88
89const char MetricsDaemon::kMetricPageFaultsLongName[] =
90 "Platform.PageFaultsLong";
91const char MetricsDaemon::kMetricPageFaultsShortName[] =
92 "Platform.PageFaultsShort";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080093
Sonny Rao4b8aebb2013-07-31 23:18:31 -070094// Swap in and Swap out
95
96const char MetricsDaemon::kMetricSwapInLongName[] =
97 "Platform.SwapInLong";
98const char MetricsDaemon::kMetricSwapInShortName[] =
99 "Platform.SwapInShort";
100
101const char MetricsDaemon::kMetricSwapOutLongName[] =
102 "Platform.SwapOutLong";
103const char MetricsDaemon::kMetricSwapOutShortName[] =
104 "Platform.SwapOutShort";
105
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700106const char MetricsDaemon::kMetricsProcStatFileName[] = "/proc/stat";
107const int MetricsDaemon::kMetricsProcStatFirstLineItemsCount = 11;
108
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700109// Thermal CPU throttling.
110
111const char MetricsDaemon::kMetricScaledCpuFrequencyName[] =
112 "Platform.CpuFrequencyThermalScaling";
113
Luigi Semenzato96360192014-06-04 10:53:35 -0700114// Zram sysfs entries.
115
116const char MetricsDaemon::kComprDataSizeName[] = "compr_data_size";
117const char MetricsDaemon::kOrigDataSizeName[] = "orig_data_size";
118const char MetricsDaemon::kZeroPagesName[] = "zero_pages";
119
Luigi Semenzato8accd332011-05-17 16:37:18 -0700120// Memory use stats collection intervals. We collect some memory use interval
121// at these intervals after boot, and we stop collecting after the last one,
122// with the assumption that in most cases the memory use won't change much
123// after that.
124static const int kMemuseIntervals[] = {
125 1 * kSecondsPerMinute, // 1 minute mark
126 4 * kSecondsPerMinute, // 5 minute mark
127 25 * kSecondsPerMinute, // 0.5 hour mark
128 120 * kSecondsPerMinute, // 2.5 hour mark
129 600 * kSecondsPerMinute, // 12.5 hour mark
130};
131
Darin Petkovf1e85e42010-06-10 15:59:53 -0700132MetricsDaemon::MetricsDaemon()
Daniel Eratc83975a2014-04-04 08:53:44 -0700133 : update_stats_timeout_id_(-1),
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800134 memuse_final_time_(0),
Luigi Semenzato8accd332011-05-17 16:37:18 -0700135 memuse_interval_index_(0),
136 read_sectors_(0),
137 write_sectors_(0),
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700138 vmstats_(),
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700139 stats_state_(kStatsShort),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700140 stats_initial_time_(0),
141 ticks_per_second_(0),
142 latest_cpu_use_ticks_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700143
Ken Mixter4c5daa42010-08-26 18:35:06 -0700144MetricsDaemon::~MetricsDaemon() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700145 if (update_stats_timeout_id_ > -1)
146 g_source_remove(update_stats_timeout_id_);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700147}
148
Luigi Semenzato8accd332011-05-17 16:37:18 -0700149double MetricsDaemon::GetActiveTime() {
150 struct timespec ts;
151 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
152 if (r < 0) {
153 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
154 return 0;
155 } else {
156 return ts.tv_sec + ((double) ts.tv_nsec) / (1000 * 1000 * 1000);
157 }
158}
159
Darin Petkov2ccef012010-05-05 16:06:37 -0700160void MetricsDaemon::Run(bool run_as_daemon) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800161 base::AtExitManager at_exit_manager;
162
Darin Petkov38d5cb02010-06-24 12:10:26 -0700163 if (run_as_daemon && daemon(0, 0) != 0)
164 return;
165
Ken Mixterccd84c02010-08-16 19:57:13 -0700166 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
167 ProcessKernelCrash();
168 }
169
170 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
171 ProcessUncleanShutdown();
172 }
173
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800174 // On OS version change, clear version stats (which are reported daily).
175 int32 version = GetOsVersionHash();
176 if (version_cycle_->Get() != version) {
177 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800178 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700179 version_cumulative_active_use_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700180 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800181 }
182
Darin Petkov38d5cb02010-06-24 12:10:26 -0700183 Loop();
Darin Petkov65b01462010-04-14 13:32:20 -0700184}
185
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800186uint32 MetricsDaemon::GetOsVersionHash() {
187 static uint32 cached_version_hash = 0;
188 static bool version_hash_is_cached = false;
189 if (version_hash_is_cached)
190 return cached_version_hash;
191 version_hash_is_cached = true;
192 std::string version;
193 if (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_VERSION", &version)) {
194 cached_version_hash = base::Hash(version);
195 } else if (testing_) {
196 cached_version_hash = 42; // return any plausible value for the hash
197 } else {
198 LOG(FATAL) << "could not find CHROMEOS_RELEASE_VERSION";
199 }
200 return cached_version_hash;
201}
202
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800203void MetricsDaemon::Init(bool testing, MetricsLibraryInterface* metrics_lib,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700204 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700205 const string& vmstats_path,
206 const string& scaling_max_freq_path,
Daniel Eratc83975a2014-04-04 08:53:44 -0700207 const string& cpuinfo_max_freq_path) {
Darin Petkov65b01462010-04-14 13:32:20 -0700208 testing_ = testing;
Darin Petkovfc91b422010-05-12 13:05:45 -0700209 DCHECK(metrics_lib != NULL);
210 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700211
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700212 // Get ticks per second (HZ) on this system.
213 // Sysconf cannot fail, so no sanity checks are needed.
214 ticks_per_second_ = sysconf(_SC_CLK_TCK);
215
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700216 daily_active_use_.reset(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800217 new PersistentInteger("Logging.DailyUseTime"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700218 version_cumulative_active_use_.reset(
219 new PersistentInteger("Logging.CumulativeDailyUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700220 version_cumulative_cpu_use_.reset(
221 new PersistentInteger("Logging.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700222
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800223 kernel_crash_interval_.reset(
224 new PersistentInteger("Logging.KernelCrashInterval"));
225 unclean_shutdown_interval_.reset(
226 new PersistentInteger("Logging.UncleanShutdownInterval"));
227 user_crash_interval_.reset(
228 new PersistentInteger("Logging.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700229
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800230 any_crashes_daily_count_.reset(
231 new PersistentInteger("Logging.AnyCrashesDaily"));
232 any_crashes_weekly_count_.reset(
233 new PersistentInteger("Logging.AnyCrashesWeekly"));
234 user_crashes_daily_count_.reset(
235 new PersistentInteger("Logging.UserCrashesDaily"));
236 user_crashes_weekly_count_.reset(
237 new PersistentInteger("Logging.UserCrashesWeekly"));
238 kernel_crashes_daily_count_.reset(
239 new PersistentInteger("Logging.KernelCrashesDaily"));
240 kernel_crashes_weekly_count_.reset(
241 new PersistentInteger("Logging.KernelCrashesWeekly"));
242 kernel_crashes_version_count_.reset(
243 new PersistentInteger("Logging.KernelCrashesSinceUpdate"));
244 unclean_shutdowns_daily_count_.reset(
245 new PersistentInteger("Logging.UncleanShutdownsDaily"));
246 unclean_shutdowns_weekly_count_.reset(
247 new PersistentInteger("Logging.UncleanShutdownsWeekly"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700248
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800249 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
250 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
251 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800252
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700253 diskstats_path_ = diskstats_path;
254 vmstats_path_ = vmstats_path;
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700255 scaling_max_freq_path_ = scaling_max_freq_path;
256 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700257 StatsReporterInit();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800258
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700259 // Start collecting meminfo stats.
260 ScheduleMeminfoCallback(kMetricMeminfoInterval);
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800261 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
262 ScheduleMemuseCallback(kMemuseIntervals[0]);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700263
Darin Petkov2ccef012010-05-05 16:06:37 -0700264 // Don't setup D-Bus and GLib in test mode.
265 if (testing)
266 return;
Darin Petkov65b01462010-04-14 13:32:20 -0700267
Darin Petkov703ec972010-04-27 11:02:18 -0700268 g_type_init();
Ben Chan6f598422013-06-22 06:29:36 -0700269 dbus_threads_init_default();
Darin Petkov65b01462010-04-14 13:32:20 -0700270
Darin Petkov703ec972010-04-27 11:02:18 -0700271 DBusError error;
272 dbus_error_init(&error);
Darin Petkov65b01462010-04-14 13:32:20 -0700273
David James3b3add52010-06-04 15:01:19 -0700274 DBusConnection* connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
Darin Petkov703ec972010-04-27 11:02:18 -0700275 LOG_IF(FATAL, dbus_error_is_set(&error)) <<
276 "No D-Bus connection: " << SAFE_MESSAGE(error);
Darin Petkov65b01462010-04-14 13:32:20 -0700277
Darin Petkov703ec972010-04-27 11:02:18 -0700278 dbus_connection_setup_with_g_main(connection, NULL);
Darin Petkov65b01462010-04-14 13:32:20 -0700279
Darin Petkov40f25732013-04-29 15:07:31 +0200280 vector<string> matches;
281 matches.push_back(
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800282 base::StringPrintf("type='signal',interface='%s',path='/',member='%s'",
283 kCrashReporterInterface,
284 kCrashReporterUserCrashSignal));
Darin Petkov40f25732013-04-29 15:07:31 +0200285
Darin Petkov703ec972010-04-27 11:02:18 -0700286 // Registers D-Bus matches for the signals we would like to catch.
Darin Petkov40f25732013-04-29 15:07:31 +0200287 for (vector<string>::const_iterator it = matches.begin();
288 it != matches.end(); ++it) {
289 const char* match = it->c_str();
Darin Petkov41e06232010-05-03 16:45:37 -0700290 DLOG(INFO) << "adding dbus match: " << match;
Darin Petkov703ec972010-04-27 11:02:18 -0700291 dbus_bus_add_match(connection, match, &error);
292 LOG_IF(FATAL, dbus_error_is_set(&error)) <<
293 "unable to add a match: " << SAFE_MESSAGE(error);
294 }
295
296 // Adds the D-Bus filter routine to be called back whenever one of
297 // the registered D-Bus matches is successful. The daemon is not
298 // activated for D-Bus messages that don't match.
299 CHECK(dbus_connection_add_filter(connection, MessageFilter, this, NULL));
Daniel Eratc83975a2014-04-04 08:53:44 -0700300
301 update_stats_timeout_id_ =
302 g_timeout_add(kUpdateStatsIntervalMs, &HandleUpdateStatsTimeout, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700303}
304
305void MetricsDaemon::Loop() {
Darin Petkov703ec972010-04-27 11:02:18 -0700306 GMainLoop* loop = g_main_loop_new(NULL, false);
307 g_main_loop_run(loop);
Darin Petkov65b01462010-04-14 13:32:20 -0700308}
309
Darin Petkov703ec972010-04-27 11:02:18 -0700310// static
311DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
312 DBusMessage* message,
313 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700314 int message_type = dbus_message_get_type(message);
315 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700316 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700317 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
318 }
319
320 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700321 const std::string interface(dbus_message_get_interface(message));
322 const std::string member(dbus_message_get_member(message));
323 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700324
325 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
326
327 DBusMessageIter iter;
328 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700329 if (interface == kCrashReporterInterface) {
330 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700331 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700332 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700333 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700334 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
335 }
336
337 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700338}
339
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700340// One might argue that parts of this should go into
341// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
342
343TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700344 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
345 std::string proc_stat_string;
346 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
347 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
348 return TimeDelta();
349 }
350
351 std::vector<std::string> proc_stat_lines;
352 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
353 if (proc_stat_lines.empty()) {
354 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
355 << ": " << proc_stat_string;
356 return TimeDelta();
357 }
358 std::vector<std::string> proc_stat_totals;
359 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
360
361 uint64 user_ticks, user_nice_ticks, system_ticks;
362 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
363 proc_stat_totals[0] != "cpu" ||
364 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
365 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
366 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
367 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
368 return TimeDelta(base::TimeDelta::FromSeconds(0));
369 }
370
371 uint64 total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
372
373 // Sanity check.
374 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
375 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
376 << " to " << total_cpu_use_ticks;
377 return TimeDelta();
378 }
379
380 uint64 diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
381 latest_cpu_use_ticks_ = total_cpu_use_ticks;
382 // Use microseconds to avoid significant truncations.
383 return base::TimeDelta::FromMicroseconds(
384 diff * 1000 * 1000 / ticks_per_second_);
385}
386
Darin Petkov1bb904e2010-06-16 15:58:06 -0700387void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700388 // Counts the active time up to now.
389 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700390
391 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800392 SendCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700393
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800394 any_crashes_daily_count_->Add(1);
395 any_crashes_weekly_count_->Add(1);
396 user_crashes_daily_count_->Add(1);
397 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700398}
399
Darin Petkov38d5cb02010-06-24 12:10:26 -0700400void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700401 // Counts the active time up to now.
402 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700403
404 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800405 SendCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700406
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800407 any_crashes_daily_count_->Add(1);
408 any_crashes_weekly_count_->Add(1);
409 kernel_crashes_daily_count_->Add(1);
410 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800411
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800412 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700413}
414
Ken Mixterccd84c02010-08-16 19:57:13 -0700415void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700416 // Counts the active time up to now.
417 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700418
419 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800420 SendCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700421
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800422 unclean_shutdowns_daily_count_->Add(1);
423 unclean_shutdowns_weekly_count_->Add(1);
424 any_crashes_daily_count_->Add(1);
425 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700426}
427
Luigi Semenzato8accd332011-05-17 16:37:18 -0700428bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700429 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800430 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700431 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700432
433 // Deletes the crash-detected file so that the daemon doesn't report
434 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800435 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700436 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700437}
438
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700439void MetricsDaemon::StatsReporterInit() {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800440 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700441 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800442 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700443 stats_state_ = kStatsLong;
444 stats_initial_time_ = GetActiveTime();
445 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700446 LOG(WARNING) << "not collecting disk stats";
447 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700448 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700449 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800450}
451
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700452void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800453 if (testing_) {
454 return;
455 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700456 g_timeout_add_seconds(wait, StatsCallbackStatic, this);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800457}
458
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700459bool MetricsDaemon::DiskStatsReadStats(long int* read_sectors,
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800460 long int* write_sectors) {
461 int nchars;
462 int nitems;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700463 bool success = false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800464 char line[200];
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700465 if (diskstats_path_.empty()) {
466 return false;
467 }
Luigi Semenzato0f132bb2011-02-28 11:17:43 -0800468 int file = HANDLE_EINTR(open(diskstats_path_.c_str(), O_RDONLY));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800469 if (file < 0) {
470 PLOG(WARNING) << "cannot open " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700471 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800472 }
473 nchars = HANDLE_EINTR(read(file, line, sizeof(line)));
474 if (nchars < 0) {
475 PLOG(WARNING) << "cannot read from " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700476 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800477 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700478 LOG_IF(WARNING, nchars == sizeof(line))
479 << "line too long in " << diskstats_path_;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800480 line[nchars] = '\0';
481 nitems = sscanf(line, "%*d %*d %ld %*d %*d %*d %ld",
482 read_sectors, write_sectors);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700483 if (nitems == 2) {
484 success = true;
485 } else {
486 LOG(WARNING) << "found " << nitems << " items in "
487 << diskstats_path_ << ", expected 2";
488 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800489 }
Mike Frysinger3e8a8512014-05-14 16:14:37 -0400490 IGNORE_EINTR(close(file));
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700491 return success;
492}
493
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700494bool MetricsDaemon::VmStatsParseStats(const char* stats,
495 struct VmstatRecord* record) {
496 // a mapping of string name to field in VmstatRecord and whether we found it
497 struct mapping {
498 const string name;
499 uint64_t* value_p;
500 bool found;
501 } map[] =
502 { { .name = "pgmajfault",
503 .value_p = &record->page_faults_,
504 .found = false },
505 { .name = "pswpin",
506 .value_p = &record->swap_in_,
507 .found = false },
508 { .name = "pswpout",
509 .value_p = &record->swap_out_,
510 .found = false }, };
511
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700512 // Each line in the file has the form
513 // <ID> <VALUE>
514 // for instance:
515 // nr_free_pages 213427
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700516 vector<string> lines;
517 Tokenize(stats, "\n", &lines);
518 for (vector<string>::iterator it = lines.begin();
519 it != lines.end(); ++it) {
520 vector<string> tokens;
521 base::SplitString(*it, ' ', &tokens);
522 if (tokens.size() == 2) {
523 for (unsigned int i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
524 if (!tokens[0].compare(map[i].name)) {
525 if (!base::StringToUint64(tokens[1], map[i].value_p))
526 return false;
527 map[i].found = true;
528 }
529 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700530 } else {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700531 LOG(WARNING) << "unexpected vmstat format";
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700532 }
533 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700534 // make sure we got all the stats
535 for (unsigned i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
536 if (map[i].found == false) {
537 LOG(WARNING) << "vmstat missing " << map[i].name;
538 return false;
539 }
540 }
541 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700542}
543
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700544bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
545 string value_string;
546 FilePath* path = new FilePath(vmstats_path_);
Ben Chan2e6543d2014-02-05 23:26:25 -0800547 if (!base::ReadFileToString(*path, &value_string)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700548 delete path;
549 LOG(WARNING) << "cannot read " << vmstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700550 return false;
551 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700552 delete path;
553 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800554}
555
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700556bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700557 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700558 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800559 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700560 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
561 return false;
562 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800563 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700564 LOG(WARNING) << "no newline in " << value_string;
565 // Continue even though the lack of newline is suspicious.
566 }
567 if (!base::StringToInt(value_string, value)) {
568 LOG(WARNING) << "cannot convert " << value_string << " to int";
569 return false;
570 }
571 return true;
572}
573
574void MetricsDaemon::SendCpuThrottleMetrics() {
575 // |max_freq| is 0 only the first time through.
576 static int max_freq = 0;
577 if (max_freq == -1)
578 // Give up, as sysfs did not report max_freq correctly.
579 return;
580 if (max_freq == 0 || testing_) {
581 // One-time initialization of max_freq. (Every time when testing.)
582 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
583 max_freq = -1;
584 return;
585 }
586 if (max_freq == 0) {
587 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
588 max_freq = -1;
589 return;
590 }
591 if (max_freq % 10000 == 1000) {
592 // Special case: system has turbo mode, and max non-turbo frequency is
593 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
594 // being multiples of (at least) 10 MHz. Although there is no guarantee
595 // of this, it seems a fairly reasonable assumption. Otherwise we should
596 // read scaling_available_frequencies, sort the frequencies, compare the
597 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
598 // hack too, no telling when it will change).
599 max_freq -= 1000;
600 }
601 }
602 int scaled_freq = 0;
603 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
604 return;
605 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
606 // scaled_freq is not the actual turbo frequency. We indicate this situation
607 // with a 101% value.
608 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800609 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700610}
611
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800612// static
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700613gboolean MetricsDaemon::StatsCallbackStatic(void* handle) {
614 (static_cast<MetricsDaemon*>(handle))->StatsCallback();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800615 return false; // one-time callback
616}
617
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700618// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700619
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700620void MetricsDaemon::StatsCallback() {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700621 long int read_sectors_now, write_sectors_now;
622 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700623 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700624 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700625 if (testing_) {
626 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700627 delta_time = stats_state_ == kStatsShort ?
628 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700629 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700630 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
631 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700632 int delta_read = read_sectors_now - read_sectors_;
633 int delta_write = write_sectors_now - write_sectors_;
634 int read_sectors_per_second = delta_read / delta_time;
635 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700636 bool vmstats_success = VmStatsReadStats(&vmstats_now);
637 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
638 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
639 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
640 uint64_t page_faults_per_second = delta_faults / delta_time;
641 uint64_t swap_in_per_second = delta_swap_in / delta_time;
642 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800643
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700644 switch (stats_state_) {
645 case kStatsShort:
646 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800647 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700648 read_sectors_per_second,
649 1,
650 kMetricSectorsIOMax,
651 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800652 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700653 write_sectors_per_second,
654 1,
655 kMetricSectorsIOMax,
656 kMetricSectorsBuckets);
657 }
658 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800659 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700660 page_faults_per_second,
661 1,
662 kMetricPageFaultsMax,
663 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800664 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700665 swap_in_per_second,
666 1,
667 kMetricPageFaultsMax,
668 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800669 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700670 swap_out_per_second,
671 1,
672 kMetricPageFaultsMax,
673 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700674 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800675 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700676 stats_state_ = kStatsLong;
677 ScheduleStatsCallback(kMetricStatsLongInterval -
678 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800679 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700680 case kStatsLong:
681 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800682 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700683 read_sectors_per_second,
684 1,
685 kMetricSectorsIOMax,
686 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800687 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700688 write_sectors_per_second,
689 1,
690 kMetricSectorsIOMax,
691 kMetricSectorsBuckets);
692 // Reset sector counters.
693 read_sectors_ = read_sectors_now;
694 write_sectors_ = write_sectors_now;
695 }
696 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800697 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700698 page_faults_per_second,
699 1,
700 kMetricPageFaultsMax,
701 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800702 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700703 swap_in_per_second,
704 1,
705 kMetricPageFaultsMax,
706 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800707 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700708 swap_out_per_second,
709 1,
710 kMetricPageFaultsMax,
711 kMetricPageFaultsBuckets);
712
713 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700714 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700715 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700716 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700717 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800718 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700719 stats_state_ = kStatsShort;
720 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800721 break;
722 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700723 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800724 }
725}
726
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700727void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
728 if (testing_) {
729 return;
730 }
731 g_timeout_add_seconds(wait, MeminfoCallbackStatic, this);
732}
733
734// static
735gboolean MetricsDaemon::MeminfoCallbackStatic(void* handle) {
736 return (static_cast<MetricsDaemon*>(handle))->MeminfoCallback();
737}
738
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700739bool MetricsDaemon::MeminfoCallback() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700740 string meminfo_raw;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700741 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800742 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700743 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
744 return false;
745 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700746 // Make both calls even if the first one fails.
747 bool success = ProcessMeminfo(meminfo_raw);
748 return ReportZram(base::FilePath(FILE_PATH_LITERAL("/sys/block/zram0"))) &&
749 success;
750}
751
752// static
753bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
754 uint64* value) {
755 std::string content;
756 if (!base::ReadFileToString(path, &content)) {
757 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
758 return false;
759 }
760 if (!base::StringToUint64(content, value)) {
761 LOG(WARNING) << "invalid integer: " << content;
762 return false;
763 }
764 return true;
765}
766
767bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
768 // Data sizes are in bytes. |zero_pages| is in number of pages.
769 uint64 compr_data_size, orig_data_size, zero_pages;
770 const size_t page_size = 4096;
771
772 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
773 &compr_data_size) ||
774 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
775 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
776 return false;
777 }
778
779 // |orig_data_size| does not include zero-filled pages.
780 orig_data_size += zero_pages * page_size;
781
782 const int compr_data_size_mb = compr_data_size >> 20;
783 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
784 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
785
786 // Report compressed size in megabytes. 100 MB or less has little impact.
787 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
788 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
789 // The compression ratio is multiplied by 100 for better resolution. The
790 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
791 // don't want samples when very little memory is being compressed.
792 if (compr_data_size_mb >= 1) {
793 SendSample("Platform.ZramCompressionRatioPercent",
794 orig_data_size * 100 / compr_data_size, 100, 600, 50);
795 }
796 // The values of interest for zero_pages are between 1MB and 1GB. The units
797 // are number of pages.
798 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
799 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
800
801 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700802}
803
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700804bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700805 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700806 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
807 { "MemFree", "MemFree" },
808 { "Buffers", "Buffers" },
809 { "Cached", "Cached" },
810 // { "SwapCached", "SwapCached" },
811 { "Active", "Active" },
812 { "Inactive", "Inactive" },
813 { "ActiveAnon", "Active(anon)" },
814 { "InactiveAnon", "Inactive(anon)" },
815 { "ActiveFile" , "Active(file)" },
816 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800817 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700818 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800819 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
820 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700821 // { "Dirty", "Dirty" },
822 // { "Writeback", "Writeback" },
823 { "AnonPages", "AnonPages" },
824 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800825 { "Shmem", "Shmem", kMeminfoOp_HistLog },
826 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700827 // { "SReclaimable", "SReclaimable" },
828 // { "SUnreclaim", "SUnreclaim" },
829 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700830 vector<MeminfoRecord> fields(fields_array,
831 fields_array + arraysize(fields_array));
832 if (!FillMeminfo(meminfo_raw, &fields)) {
833 return false;
834 }
835 int total_memory = fields[0].value;
836 if (total_memory == 0) {
837 // this "cannot happen"
838 LOG(WARNING) << "borked meminfo parser";
839 return false;
840 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800841 int swap_total = 0;
842 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700843 // Send all fields retrieved, except total memory.
844 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800845 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
846 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800847 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800848 switch (fields[i].op) {
849 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800850 // report value as percent of total memory
851 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800852 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800853 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800854 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800855 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800856 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800857 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800858 case kMeminfoOp_SwapTotal:
859 swap_total = fields[i].value;
860 case kMeminfoOp_SwapFree:
861 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800862 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700863 }
864 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800865 if (swap_total > 0) {
866 int swap_used = swap_total - swap_free;
867 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800868 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
869 SendLinearSample("Platform.MeminfoSwapUsedPercent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800870 100, 101);
871 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700872 return true;
873}
874
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700875bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
876 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700877 vector<string> lines;
878 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700879
880 // Scan meminfo output and collect field values. Each field name has to
881 // match a meminfo entry (case insensitive) after removing non-alpha
882 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700883 unsigned int ifield = 0;
884 for (unsigned int iline = 0;
885 iline < nlines && ifield < fields->size();
886 iline++) {
887 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700888 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700889 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
890 // Name matches. Parse value and save.
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700891 char* rest;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700892 (*fields)[ifield].value =
893 static_cast<int>(strtol(tokens[1].c_str(), &rest, 10));
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700894 if (*rest != '\0') {
895 LOG(WARNING) << "missing meminfo value";
896 return false;
897 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700898 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700899 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700900 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700901 if (ifield < fields->size()) {
902 // End of input reached while scanning.
903 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
904 << " and following";
905 return false;
906 }
907 return true;
908}
909
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800910void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700911 if (testing_) {
912 return;
913 }
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800914 g_timeout_add_seconds(interval, MemuseCallbackStatic, this);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700915}
916
917// static
918gboolean MetricsDaemon::MemuseCallbackStatic(void* handle) {
919 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(handle);
920 daemon->MemuseCallback();
921 return false;
922}
923
924void MetricsDaemon::MemuseCallback() {
925 // Since we only care about active time (i.e. uptime minus sleep time) but
926 // the callbacks are driven by real time (uptime), we check if we should
927 // reschedule this callback due to intervening sleep periods.
928 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800929 // Avoid intervals of less than one second.
930 double remaining_time = ceil(memuse_final_time_ - now);
931 if (remaining_time > 0) {
932 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700933 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800934 // Report stats and advance the measurement interval unless there are
935 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700936 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800937 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
938 double interval = kMemuseIntervals[memuse_interval_index_++];
939 memuse_final_time_ = now + interval;
940 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700941 }
942 }
943}
944
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700945bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700946 string meminfo_raw;
947 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800948 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700949 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
950 return false;
951 }
952 return ProcessMemuse(meminfo_raw);
953}
954
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700955bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700956 static const MeminfoRecord fields_array[] = {
957 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
958 { "ActiveAnon", "Active(anon)" },
959 { "InactiveAnon", "Inactive(anon)" },
960 };
961 vector<MeminfoRecord> fields(fields_array,
962 fields_array + arraysize(fields_array));
963 if (!FillMeminfo(meminfo_raw, &fields)) {
964 return false;
965 }
966 int total = fields[0].value;
967 int active_anon = fields[1].value;
968 int inactive_anon = fields[2].value;
969 if (total == 0) {
970 // this "cannot happen"
971 LOG(WARNING) << "borked meminfo parser";
972 return false;
973 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800974 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
975 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800976 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -0700977 100, 101);
978 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700979}
980
Luigi Semenzato5ef2e392014-04-15 15:15:02 -0700981void MetricsDaemon::ReportDailyUse(int use_seconds) {
982 if (use_seconds <= 0)
Darin Petkov1bb904e2010-06-16 15:58:06 -0700983 return;
984
Luigi Semenzato5ef2e392014-04-15 15:15:02 -0700985 int minutes = (use_seconds + kSecondsPerMinute / 2) / kSecondsPerMinute;
986 SendSample("Logging.DailyUseTime",
987 minutes,
988 1,
989 kMinutesPerDay * 30 * 2, // cumulative---two months worth
990 50);
Darin Petkovf1e85e42010-06-10 15:59:53 -0700991}
992
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800993void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -0700994 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -0700995 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700996}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700997
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700998void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800999 // Report the number of crashes for this OS version, but don't clear the
1000 // counter. It is cleared elsewhere on version change.
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001001 int64 crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001002 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001003 crashes_count,
1004 1, // value of first bucket
1005 500, // value of last bucket
1006 100); // number of buckets
1007
1008
1009 int64 cpu_use_ms = version_cumulative_cpu_use_->Get();
1010 SendSample(version_cumulative_cpu_use_->Name(),
1011 cpu_use_ms / 1000, // stat is in seconds
1012 1, // device may be used very little...
1013 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
1014 100);
1015
1016 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
1017 // can be zero. Avoid division by zero.
1018 if (cpu_use_ms > 0) {
1019 // Send the crash frequency since update in number of crashes per CPU year.
1020 SendSample("Logging.KernelCrashesPerCpuYear",
1021 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
1022 1,
1023 1000 * 1000, // about one crash every 30s of CPU time
1024 100);
1025 }
1026
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001027 int64 active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001028 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001029 SendSample(version_cumulative_active_use_->Name(),
1030 active_use_seconds / 1000, // stat is in seconds
1031 1, // device may be used very little...
1032 8 * 1000 * 1000, // ... or a lot (about 90 days)
1033 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001034 // Same as above, but per year of active time.
1035 SendSample("Logging.KernelCrashesPerActiveYear",
1036 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
1037 1,
1038 1000 * 1000, // about one crash every 30s of active time
1039 100);
1040 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001041}
1042
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001043void MetricsDaemon::SendDailyUseSample(
1044 const scoped_ptr<PersistentInteger>& use) {
1045 SendSample(use->Name(),
1046 use->GetAndClear(),
1047 1, // value of first bucket
1048 kSecondsPerDay, // value of last bucket
1049 50); // number of buckets
1050}
1051
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001052void MetricsDaemon::SendCrashIntervalSample(
1053 const scoped_ptr<PersistentInteger>& interval) {
1054 SendSample(interval->Name(),
1055 interval->GetAndClear(),
1056 1, // value of first bucket
1057 4 * kSecondsPerWeek, // value of last bucket
1058 50); // number of buckets
1059}
1060
1061void MetricsDaemon::SendCrashFrequencySample(
1062 const scoped_ptr<PersistentInteger>& frequency) {
1063 SendSample(frequency->Name(),
1064 frequency->GetAndClear(),
1065 1, // value of first bucket
1066 100, // value of last bucket
1067 50); // number of buckets
1068}
1069
1070void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001071 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001072 // TODO(semenzato): add a proper linear histogram to the Chrome external
1073 // metrics API.
1074 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1075 metrics_lib_->SendEnumToUMA(name, sample, max);
1076}
Daniel Eratc83975a2014-04-04 08:53:44 -07001077
1078void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
1079 Time now_wall_time) {
1080 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001081 daily_active_use_->Add(elapsed_seconds);
1082 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -07001083 user_crash_interval_->Add(elapsed_seconds);
1084 kernel_crash_interval_->Add(elapsed_seconds);
1085 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
1086 last_update_stats_time_ = now_ticks;
1087
1088 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
1089 const int day = since_epoch.InDays();
1090 const int week = day / 7;
1091
1092 if (daily_cycle_->Get() != day) {
1093 daily_cycle_->Set(day);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001094 SendDailyUseSample(daily_active_use_);
1095 SendDailyUseSample(version_cumulative_active_use_);
Daniel Eratc83975a2014-04-04 08:53:44 -07001096 SendCrashFrequencySample(any_crashes_daily_count_);
1097 SendCrashFrequencySample(user_crashes_daily_count_);
1098 SendCrashFrequencySample(kernel_crashes_daily_count_);
1099 SendCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001100 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -07001101 }
1102
1103 if (weekly_cycle_->Get() != week) {
1104 weekly_cycle_->Set(week);
1105 SendCrashFrequencySample(any_crashes_weekly_count_);
1106 SendCrashFrequencySample(user_crashes_weekly_count_);
1107 SendCrashFrequencySample(kernel_crashes_weekly_count_);
1108 SendCrashFrequencySample(unclean_shutdowns_weekly_count_);
1109 }
1110}
1111
1112// static
1113gboolean MetricsDaemon::HandleUpdateStatsTimeout(gpointer data) {
1114 static_cast<MetricsDaemon*>(data)->UpdateStats(TimeTicks::Now(), Time::Now());
1115 return TRUE;
1116}