blob: 47d74fa98bed757097fd9c532a936a1c8fe6039f [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 Semenzato8accd332011-05-17 16:37:18 -0700114// Memory use stats collection intervals. We collect some memory use interval
115// at these intervals after boot, and we stop collecting after the last one,
116// with the assumption that in most cases the memory use won't change much
117// after that.
118static const int kMemuseIntervals[] = {
119 1 * kSecondsPerMinute, // 1 minute mark
120 4 * kSecondsPerMinute, // 5 minute mark
121 25 * kSecondsPerMinute, // 0.5 hour mark
122 120 * kSecondsPerMinute, // 2.5 hour mark
123 600 * kSecondsPerMinute, // 12.5 hour mark
124};
125
Darin Petkovf1e85e42010-06-10 15:59:53 -0700126MetricsDaemon::MetricsDaemon()
Daniel Eratc83975a2014-04-04 08:53:44 -0700127 : update_stats_timeout_id_(-1),
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800128 memuse_final_time_(0),
Luigi Semenzato8accd332011-05-17 16:37:18 -0700129 memuse_interval_index_(0),
130 read_sectors_(0),
131 write_sectors_(0),
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700132 vmstats_(),
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700133 stats_state_(kStatsShort),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700134 stats_initial_time_(0),
135 ticks_per_second_(0),
136 latest_cpu_use_ticks_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700137
Ken Mixter4c5daa42010-08-26 18:35:06 -0700138MetricsDaemon::~MetricsDaemon() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700139 if (update_stats_timeout_id_ > -1)
140 g_source_remove(update_stats_timeout_id_);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700141}
142
Luigi Semenzato8accd332011-05-17 16:37:18 -0700143double MetricsDaemon::GetActiveTime() {
144 struct timespec ts;
145 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
146 if (r < 0) {
147 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
148 return 0;
149 } else {
150 return ts.tv_sec + ((double) ts.tv_nsec) / (1000 * 1000 * 1000);
151 }
152}
153
Darin Petkov2ccef012010-05-05 16:06:37 -0700154void MetricsDaemon::Run(bool run_as_daemon) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800155 base::AtExitManager at_exit_manager;
156
Darin Petkov38d5cb02010-06-24 12:10:26 -0700157 if (run_as_daemon && daemon(0, 0) != 0)
158 return;
159
Ken Mixterccd84c02010-08-16 19:57:13 -0700160 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
161 ProcessKernelCrash();
162 }
163
164 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
165 ProcessUncleanShutdown();
166 }
167
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800168 // On OS version change, clear version stats (which are reported daily).
169 int32 version = GetOsVersionHash();
170 if (version_cycle_->Get() != version) {
171 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800172 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700173 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800174 }
175
Darin Petkov38d5cb02010-06-24 12:10:26 -0700176 Loop();
Darin Petkov65b01462010-04-14 13:32:20 -0700177}
178
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800179uint32 MetricsDaemon::GetOsVersionHash() {
180 static uint32 cached_version_hash = 0;
181 static bool version_hash_is_cached = false;
182 if (version_hash_is_cached)
183 return cached_version_hash;
184 version_hash_is_cached = true;
185 std::string version;
186 if (base::SysInfo::GetLsbReleaseValue("CHROMEOS_RELEASE_VERSION", &version)) {
187 cached_version_hash = base::Hash(version);
188 } else if (testing_) {
189 cached_version_hash = 42; // return any plausible value for the hash
190 } else {
191 LOG(FATAL) << "could not find CHROMEOS_RELEASE_VERSION";
192 }
193 return cached_version_hash;
194}
195
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800196void MetricsDaemon::Init(bool testing, MetricsLibraryInterface* metrics_lib,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700197 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700198 const string& vmstats_path,
199 const string& scaling_max_freq_path,
Daniel Eratc83975a2014-04-04 08:53:44 -0700200 const string& cpuinfo_max_freq_path) {
Darin Petkov65b01462010-04-14 13:32:20 -0700201 testing_ = testing;
Darin Petkovfc91b422010-05-12 13:05:45 -0700202 DCHECK(metrics_lib != NULL);
203 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700204
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700205 // Get ticks per second (HZ) on this system.
206 // Sysconf cannot fail, so no sanity checks are needed.
207 ticks_per_second_ = sysconf(_SC_CLK_TCK);
208
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800209 daily_use_.reset(
210 new PersistentInteger("Logging.DailyUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700211 version_cumulative_cpu_use_.reset(
212 new PersistentInteger("Logging.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700213
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800214 kernel_crash_interval_.reset(
215 new PersistentInteger("Logging.KernelCrashInterval"));
216 unclean_shutdown_interval_.reset(
217 new PersistentInteger("Logging.UncleanShutdownInterval"));
218 user_crash_interval_.reset(
219 new PersistentInteger("Logging.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700220
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800221 any_crashes_daily_count_.reset(
222 new PersistentInteger("Logging.AnyCrashesDaily"));
223 any_crashes_weekly_count_.reset(
224 new PersistentInteger("Logging.AnyCrashesWeekly"));
225 user_crashes_daily_count_.reset(
226 new PersistentInteger("Logging.UserCrashesDaily"));
227 user_crashes_weekly_count_.reset(
228 new PersistentInteger("Logging.UserCrashesWeekly"));
229 kernel_crashes_daily_count_.reset(
230 new PersistentInteger("Logging.KernelCrashesDaily"));
231 kernel_crashes_weekly_count_.reset(
232 new PersistentInteger("Logging.KernelCrashesWeekly"));
233 kernel_crashes_version_count_.reset(
234 new PersistentInteger("Logging.KernelCrashesSinceUpdate"));
235 unclean_shutdowns_daily_count_.reset(
236 new PersistentInteger("Logging.UncleanShutdownsDaily"));
237 unclean_shutdowns_weekly_count_.reset(
238 new PersistentInteger("Logging.UncleanShutdownsWeekly"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700239
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800240 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
241 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
242 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800243
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700244 diskstats_path_ = diskstats_path;
245 vmstats_path_ = vmstats_path;
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700246 scaling_max_freq_path_ = scaling_max_freq_path;
247 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700248 StatsReporterInit();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800249
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700250 // Start collecting meminfo stats.
251 ScheduleMeminfoCallback(kMetricMeminfoInterval);
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800252 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
253 ScheduleMemuseCallback(kMemuseIntervals[0]);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700254
Darin Petkov2ccef012010-05-05 16:06:37 -0700255 // Don't setup D-Bus and GLib in test mode.
256 if (testing)
257 return;
Darin Petkov65b01462010-04-14 13:32:20 -0700258
Darin Petkov703ec972010-04-27 11:02:18 -0700259 g_type_init();
Ben Chan6f598422013-06-22 06:29:36 -0700260 dbus_threads_init_default();
Darin Petkov65b01462010-04-14 13:32:20 -0700261
Darin Petkov703ec972010-04-27 11:02:18 -0700262 DBusError error;
263 dbus_error_init(&error);
Darin Petkov65b01462010-04-14 13:32:20 -0700264
David James3b3add52010-06-04 15:01:19 -0700265 DBusConnection* connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
Darin Petkov703ec972010-04-27 11:02:18 -0700266 LOG_IF(FATAL, dbus_error_is_set(&error)) <<
267 "No D-Bus connection: " << SAFE_MESSAGE(error);
Darin Petkov65b01462010-04-14 13:32:20 -0700268
Darin Petkov703ec972010-04-27 11:02:18 -0700269 dbus_connection_setup_with_g_main(connection, NULL);
Darin Petkov65b01462010-04-14 13:32:20 -0700270
Darin Petkov40f25732013-04-29 15:07:31 +0200271 vector<string> matches;
272 matches.push_back(
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800273 base::StringPrintf("type='signal',interface='%s',path='/',member='%s'",
274 kCrashReporterInterface,
275 kCrashReporterUserCrashSignal));
Darin Petkov40f25732013-04-29 15:07:31 +0200276
Darin Petkov703ec972010-04-27 11:02:18 -0700277 // Registers D-Bus matches for the signals we would like to catch.
Darin Petkov40f25732013-04-29 15:07:31 +0200278 for (vector<string>::const_iterator it = matches.begin();
279 it != matches.end(); ++it) {
280 const char* match = it->c_str();
Darin Petkov41e06232010-05-03 16:45:37 -0700281 DLOG(INFO) << "adding dbus match: " << match;
Darin Petkov703ec972010-04-27 11:02:18 -0700282 dbus_bus_add_match(connection, match, &error);
283 LOG_IF(FATAL, dbus_error_is_set(&error)) <<
284 "unable to add a match: " << SAFE_MESSAGE(error);
285 }
286
287 // Adds the D-Bus filter routine to be called back whenever one of
288 // the registered D-Bus matches is successful. The daemon is not
289 // activated for D-Bus messages that don't match.
290 CHECK(dbus_connection_add_filter(connection, MessageFilter, this, NULL));
Daniel Eratc83975a2014-04-04 08:53:44 -0700291
292 update_stats_timeout_id_ =
293 g_timeout_add(kUpdateStatsIntervalMs, &HandleUpdateStatsTimeout, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700294}
295
296void MetricsDaemon::Loop() {
Darin Petkov703ec972010-04-27 11:02:18 -0700297 GMainLoop* loop = g_main_loop_new(NULL, false);
298 g_main_loop_run(loop);
Darin Petkov65b01462010-04-14 13:32:20 -0700299}
300
Darin Petkov703ec972010-04-27 11:02:18 -0700301// static
302DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
303 DBusMessage* message,
304 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700305 int message_type = dbus_message_get_type(message);
306 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700307 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700308 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
309 }
310
311 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700312 const std::string interface(dbus_message_get_interface(message));
313 const std::string member(dbus_message_get_member(message));
314 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700315
316 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
317
318 DBusMessageIter iter;
319 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700320 if (interface == kCrashReporterInterface) {
321 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700322 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700323 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700324 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700325 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
326 }
327
328 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700329}
330
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700331// One might argue that parts of this should go into
332// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
333
334TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700335 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
336 std::string proc_stat_string;
337 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
338 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
339 return TimeDelta();
340 }
341
342 std::vector<std::string> proc_stat_lines;
343 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
344 if (proc_stat_lines.empty()) {
345 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
346 << ": " << proc_stat_string;
347 return TimeDelta();
348 }
349 std::vector<std::string> proc_stat_totals;
350 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
351
352 uint64 user_ticks, user_nice_ticks, system_ticks;
353 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
354 proc_stat_totals[0] != "cpu" ||
355 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
356 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
357 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
358 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
359 return TimeDelta(base::TimeDelta::FromSeconds(0));
360 }
361
362 uint64 total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
363
364 // Sanity check.
365 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
366 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
367 << " to " << total_cpu_use_ticks;
368 return TimeDelta();
369 }
370
371 uint64 diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
372 latest_cpu_use_ticks_ = total_cpu_use_ticks;
373 // Use microseconds to avoid significant truncations.
374 return base::TimeDelta::FromMicroseconds(
375 diff * 1000 * 1000 / ticks_per_second_);
376}
377
Darin Petkov1bb904e2010-06-16 15:58:06 -0700378void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700379 // Counts the active time up to now.
380 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700381
382 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800383 SendCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700384
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800385 any_crashes_daily_count_->Add(1);
386 any_crashes_weekly_count_->Add(1);
387 user_crashes_daily_count_->Add(1);
388 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700389}
390
Darin Petkov38d5cb02010-06-24 12:10:26 -0700391void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700392 // Counts the active time up to now.
393 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700394
395 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800396 SendCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700397
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800398 any_crashes_daily_count_->Add(1);
399 any_crashes_weekly_count_->Add(1);
400 kernel_crashes_daily_count_->Add(1);
401 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800402
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800403 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700404}
405
Ken Mixterccd84c02010-08-16 19:57:13 -0700406void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700407 // Counts the active time up to now.
408 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700409
410 // Reports the active use time since the last crash and resets it.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800411 SendCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700412
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800413 unclean_shutdowns_daily_count_->Add(1);
414 unclean_shutdowns_weekly_count_->Add(1);
415 any_crashes_daily_count_->Add(1);
416 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700417}
418
Luigi Semenzato8accd332011-05-17 16:37:18 -0700419bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700420 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800421 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700422 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700423
424 // Deletes the crash-detected file so that the daemon doesn't report
425 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800426 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700427 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700428}
429
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700430void MetricsDaemon::StatsReporterInit() {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800431 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700432 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800433 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700434 stats_state_ = kStatsLong;
435 stats_initial_time_ = GetActiveTime();
436 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700437 LOG(WARNING) << "not collecting disk stats";
438 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700439 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700440 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800441}
442
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700443void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800444 if (testing_) {
445 return;
446 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700447 g_timeout_add_seconds(wait, StatsCallbackStatic, this);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800448}
449
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700450bool MetricsDaemon::DiskStatsReadStats(long int* read_sectors,
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800451 long int* write_sectors) {
452 int nchars;
453 int nitems;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700454 bool success = false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800455 char line[200];
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700456 if (diskstats_path_.empty()) {
457 return false;
458 }
Luigi Semenzato0f132bb2011-02-28 11:17:43 -0800459 int file = HANDLE_EINTR(open(diskstats_path_.c_str(), O_RDONLY));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800460 if (file < 0) {
461 PLOG(WARNING) << "cannot open " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700462 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800463 }
464 nchars = HANDLE_EINTR(read(file, line, sizeof(line)));
465 if (nchars < 0) {
466 PLOG(WARNING) << "cannot read from " << diskstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700467 return false;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800468 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700469 LOG_IF(WARNING, nchars == sizeof(line))
470 << "line too long in " << diskstats_path_;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800471 line[nchars] = '\0';
472 nitems = sscanf(line, "%*d %*d %ld %*d %*d %*d %ld",
473 read_sectors, write_sectors);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700474 if (nitems == 2) {
475 success = true;
476 } else {
477 LOG(WARNING) << "found " << nitems << " items in "
478 << diskstats_path_ << ", expected 2";
479 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800480 }
481 HANDLE_EINTR(close(file));
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700482 return success;
483}
484
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700485bool MetricsDaemon::VmStatsParseStats(const char* stats,
486 struct VmstatRecord* record) {
487 // a mapping of string name to field in VmstatRecord and whether we found it
488 struct mapping {
489 const string name;
490 uint64_t* value_p;
491 bool found;
492 } map[] =
493 { { .name = "pgmajfault",
494 .value_p = &record->page_faults_,
495 .found = false },
496 { .name = "pswpin",
497 .value_p = &record->swap_in_,
498 .found = false },
499 { .name = "pswpout",
500 .value_p = &record->swap_out_,
501 .found = false }, };
502
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700503 // Each line in the file has the form
504 // <ID> <VALUE>
505 // for instance:
506 // nr_free_pages 213427
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700507 vector<string> lines;
508 Tokenize(stats, "\n", &lines);
509 for (vector<string>::iterator it = lines.begin();
510 it != lines.end(); ++it) {
511 vector<string> tokens;
512 base::SplitString(*it, ' ', &tokens);
513 if (tokens.size() == 2) {
514 for (unsigned int i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
515 if (!tokens[0].compare(map[i].name)) {
516 if (!base::StringToUint64(tokens[1], map[i].value_p))
517 return false;
518 map[i].found = true;
519 }
520 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700521 } else {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700522 LOG(WARNING) << "unexpected vmstat format";
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700523 }
524 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700525 // make sure we got all the stats
526 for (unsigned i = 0; i < sizeof(map)/sizeof(struct mapping); i++) {
527 if (map[i].found == false) {
528 LOG(WARNING) << "vmstat missing " << map[i].name;
529 return false;
530 }
531 }
532 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700533}
534
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700535bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
536 string value_string;
537 FilePath* path = new FilePath(vmstats_path_);
Ben Chan2e6543d2014-02-05 23:26:25 -0800538 if (!base::ReadFileToString(*path, &value_string)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700539 delete path;
540 LOG(WARNING) << "cannot read " << vmstats_path_;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700541 return false;
542 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700543 delete path;
544 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800545}
546
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700547bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700548 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700549 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800550 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700551 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
552 return false;
553 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800554 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700555 LOG(WARNING) << "no newline in " << value_string;
556 // Continue even though the lack of newline is suspicious.
557 }
558 if (!base::StringToInt(value_string, value)) {
559 LOG(WARNING) << "cannot convert " << value_string << " to int";
560 return false;
561 }
562 return true;
563}
564
565void MetricsDaemon::SendCpuThrottleMetrics() {
566 // |max_freq| is 0 only the first time through.
567 static int max_freq = 0;
568 if (max_freq == -1)
569 // Give up, as sysfs did not report max_freq correctly.
570 return;
571 if (max_freq == 0 || testing_) {
572 // One-time initialization of max_freq. (Every time when testing.)
573 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
574 max_freq = -1;
575 return;
576 }
577 if (max_freq == 0) {
578 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
579 max_freq = -1;
580 return;
581 }
582 if (max_freq % 10000 == 1000) {
583 // Special case: system has turbo mode, and max non-turbo frequency is
584 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
585 // being multiples of (at least) 10 MHz. Although there is no guarantee
586 // of this, it seems a fairly reasonable assumption. Otherwise we should
587 // read scaling_available_frequencies, sort the frequencies, compare the
588 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
589 // hack too, no telling when it will change).
590 max_freq -= 1000;
591 }
592 }
593 int scaled_freq = 0;
594 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
595 return;
596 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
597 // scaled_freq is not the actual turbo frequency. We indicate this situation
598 // with a 101% value.
599 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800600 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700601}
602
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800603// static
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700604gboolean MetricsDaemon::StatsCallbackStatic(void* handle) {
605 (static_cast<MetricsDaemon*>(handle))->StatsCallback();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800606 return false; // one-time callback
607}
608
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700609// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700610
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700611void MetricsDaemon::StatsCallback() {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700612 long int read_sectors_now, write_sectors_now;
613 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700614 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700615 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700616 if (testing_) {
617 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700618 delta_time = stats_state_ == kStatsShort ?
619 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700620 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700621 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
622 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700623 int delta_read = read_sectors_now - read_sectors_;
624 int delta_write = write_sectors_now - write_sectors_;
625 int read_sectors_per_second = delta_read / delta_time;
626 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700627 bool vmstats_success = VmStatsReadStats(&vmstats_now);
628 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
629 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
630 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
631 uint64_t page_faults_per_second = delta_faults / delta_time;
632 uint64_t swap_in_per_second = delta_swap_in / delta_time;
633 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800634
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700635 switch (stats_state_) {
636 case kStatsShort:
637 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800638 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700639 read_sectors_per_second,
640 1,
641 kMetricSectorsIOMax,
642 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800643 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700644 write_sectors_per_second,
645 1,
646 kMetricSectorsIOMax,
647 kMetricSectorsBuckets);
648 }
649 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800650 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700651 page_faults_per_second,
652 1,
653 kMetricPageFaultsMax,
654 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800655 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700656 swap_in_per_second,
657 1,
658 kMetricPageFaultsMax,
659 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800660 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700661 swap_out_per_second,
662 1,
663 kMetricPageFaultsMax,
664 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700665 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800666 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700667 stats_state_ = kStatsLong;
668 ScheduleStatsCallback(kMetricStatsLongInterval -
669 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800670 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700671 case kStatsLong:
672 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800673 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700674 read_sectors_per_second,
675 1,
676 kMetricSectorsIOMax,
677 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800678 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700679 write_sectors_per_second,
680 1,
681 kMetricSectorsIOMax,
682 kMetricSectorsBuckets);
683 // Reset sector counters.
684 read_sectors_ = read_sectors_now;
685 write_sectors_ = write_sectors_now;
686 }
687 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800688 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700689 page_faults_per_second,
690 1,
691 kMetricPageFaultsMax,
692 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800693 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700694 swap_in_per_second,
695 1,
696 kMetricPageFaultsMax,
697 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800698 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700699 swap_out_per_second,
700 1,
701 kMetricPageFaultsMax,
702 kMetricPageFaultsBuckets);
703
704 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700705 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700706 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700707 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700708 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800709 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700710 stats_state_ = kStatsShort;
711 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800712 break;
713 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700714 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800715 }
716}
717
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700718void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
719 if (testing_) {
720 return;
721 }
722 g_timeout_add_seconds(wait, MeminfoCallbackStatic, this);
723}
724
725// static
726gboolean MetricsDaemon::MeminfoCallbackStatic(void* handle) {
727 return (static_cast<MetricsDaemon*>(handle))->MeminfoCallback();
728}
729
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700730bool MetricsDaemon::MeminfoCallback() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700731 string meminfo_raw;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700732 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800733 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700734 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
735 return false;
736 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700737 return ProcessMeminfo(meminfo_raw);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700738}
739
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700740bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700741 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700742 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
743 { "MemFree", "MemFree" },
744 { "Buffers", "Buffers" },
745 { "Cached", "Cached" },
746 // { "SwapCached", "SwapCached" },
747 { "Active", "Active" },
748 { "Inactive", "Inactive" },
749 { "ActiveAnon", "Active(anon)" },
750 { "InactiveAnon", "Inactive(anon)" },
751 { "ActiveFile" , "Active(file)" },
752 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800753 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700754 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800755 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
756 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700757 // { "Dirty", "Dirty" },
758 // { "Writeback", "Writeback" },
759 { "AnonPages", "AnonPages" },
760 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800761 { "Shmem", "Shmem", kMeminfoOp_HistLog },
762 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700763 // { "SReclaimable", "SReclaimable" },
764 // { "SUnreclaim", "SUnreclaim" },
765 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700766 vector<MeminfoRecord> fields(fields_array,
767 fields_array + arraysize(fields_array));
768 if (!FillMeminfo(meminfo_raw, &fields)) {
769 return false;
770 }
771 int total_memory = fields[0].value;
772 if (total_memory == 0) {
773 // this "cannot happen"
774 LOG(WARNING) << "borked meminfo parser";
775 return false;
776 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800777 int swap_total = 0;
778 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700779 // Send all fields retrieved, except total memory.
780 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800781 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
782 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800783 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800784 switch (fields[i].op) {
785 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800786 // report value as percent of total memory
787 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800788 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800789 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800790 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800791 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800792 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800793 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800794 case kMeminfoOp_SwapTotal:
795 swap_total = fields[i].value;
796 case kMeminfoOp_SwapFree:
797 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800798 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700799 }
800 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800801 if (swap_total > 0) {
802 int swap_used = swap_total - swap_free;
803 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800804 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
805 SendLinearSample("Platform.MeminfoSwapUsedPercent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800806 100, 101);
807 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700808 return true;
809}
810
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700811bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
812 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700813 vector<string> lines;
814 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700815
816 // Scan meminfo output and collect field values. Each field name has to
817 // match a meminfo entry (case insensitive) after removing non-alpha
818 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700819 unsigned int ifield = 0;
820 for (unsigned int iline = 0;
821 iline < nlines && ifield < fields->size();
822 iline++) {
823 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700824 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700825 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
826 // Name matches. Parse value and save.
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700827 char* rest;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700828 (*fields)[ifield].value =
829 static_cast<int>(strtol(tokens[1].c_str(), &rest, 10));
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700830 if (*rest != '\0') {
831 LOG(WARNING) << "missing meminfo value";
832 return false;
833 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700834 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700835 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700836 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700837 if (ifield < fields->size()) {
838 // End of input reached while scanning.
839 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
840 << " and following";
841 return false;
842 }
843 return true;
844}
845
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800846void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700847 if (testing_) {
848 return;
849 }
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800850 g_timeout_add_seconds(interval, MemuseCallbackStatic, this);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700851}
852
853// static
854gboolean MetricsDaemon::MemuseCallbackStatic(void* handle) {
855 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(handle);
856 daemon->MemuseCallback();
857 return false;
858}
859
860void MetricsDaemon::MemuseCallback() {
861 // Since we only care about active time (i.e. uptime minus sleep time) but
862 // the callbacks are driven by real time (uptime), we check if we should
863 // reschedule this callback due to intervening sleep periods.
864 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800865 // Avoid intervals of less than one second.
866 double remaining_time = ceil(memuse_final_time_ - now);
867 if (remaining_time > 0) {
868 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700869 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800870 // Report stats and advance the measurement interval unless there are
871 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700872 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800873 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
874 double interval = kMemuseIntervals[memuse_interval_index_++];
875 memuse_final_time_ = now + interval;
876 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700877 }
878 }
879}
880
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700881bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700882 string meminfo_raw;
883 const FilePath meminfo_path("/proc/meminfo");
Ben Chan2e6543d2014-02-05 23:26:25 -0800884 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700885 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
886 return false;
887 }
888 return ProcessMemuse(meminfo_raw);
889}
890
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700891bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700892 static const MeminfoRecord fields_array[] = {
893 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
894 { "ActiveAnon", "Active(anon)" },
895 { "InactiveAnon", "Inactive(anon)" },
896 };
897 vector<MeminfoRecord> fields(fields_array,
898 fields_array + arraysize(fields_array));
899 if (!FillMeminfo(meminfo_raw, &fields)) {
900 return false;
901 }
902 int total = fields[0].value;
903 int active_anon = fields[1].value;
904 int inactive_anon = fields[2].value;
905 if (total == 0) {
906 // this "cannot happen"
907 LOG(WARNING) << "borked meminfo parser";
908 return false;
909 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800910 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
911 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800912 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -0700913 100, 101);
914 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700915}
916
Luigi Semenzato5ef2e392014-04-15 15:15:02 -0700917void MetricsDaemon::ReportDailyUse(int use_seconds) {
918 if (use_seconds <= 0)
Darin Petkov1bb904e2010-06-16 15:58:06 -0700919 return;
920
Luigi Semenzato5ef2e392014-04-15 15:15:02 -0700921 int minutes = (use_seconds + kSecondsPerMinute / 2) / kSecondsPerMinute;
922 SendSample("Logging.DailyUseTime",
923 minutes,
924 1,
925 kMinutesPerDay * 30 * 2, // cumulative---two months worth
926 50);
Darin Petkovf1e85e42010-06-10 15:59:53 -0700927}
928
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800929void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -0700930 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -0700931 DLOG(INFO) << "received metric: " << name << " " << sample << " "
932 << min << " " << max << " " << nbuckets;
933 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700934}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700935
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700936void MetricsDaemon::SendKernelCrashesCumulativeCountStats(
937 int64 active_use_seconds) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800938 // Report the number of crashes for this OS version, but don't clear the
939 // counter. It is cleared elsewhere on version change.
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700940 int64 crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800941 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700942 crashes_count,
943 1, // value of first bucket
944 500, // value of last bucket
945 100); // number of buckets
946
947
948 int64 cpu_use_ms = version_cumulative_cpu_use_->Get();
949 SendSample(version_cumulative_cpu_use_->Name(),
950 cpu_use_ms / 1000, // stat is in seconds
951 1, // device may be used very little...
952 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
953 100);
954
955 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
956 // can be zero. Avoid division by zero.
957 if (cpu_use_ms > 0) {
958 // Send the crash frequency since update in number of crashes per CPU year.
959 SendSample("Logging.KernelCrashesPerCpuYear",
960 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
961 1,
962 1000 * 1000, // about one crash every 30s of CPU time
963 100);
964 }
965
966 if (active_use_seconds > 0) {
967 // Same as above, but per year of active time.
968 SendSample("Logging.KernelCrashesPerActiveYear",
969 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
970 1,
971 1000 * 1000, // about one crash every 30s of active time
972 100);
973 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800974}
975
976void MetricsDaemon::SendCrashIntervalSample(
977 const scoped_ptr<PersistentInteger>& interval) {
978 SendSample(interval->Name(),
979 interval->GetAndClear(),
980 1, // value of first bucket
981 4 * kSecondsPerWeek, // value of last bucket
982 50); // number of buckets
983}
984
985void MetricsDaemon::SendCrashFrequencySample(
986 const scoped_ptr<PersistentInteger>& frequency) {
987 SendSample(frequency->Name(),
988 frequency->GetAndClear(),
989 1, // value of first bucket
990 100, // value of last bucket
991 50); // number of buckets
992}
993
994void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700995 int max, int nbuckets) {
996 DLOG(INFO) << "received linear metric: " << name << " " << sample << " "
997 << max << " " << nbuckets;
998 // TODO(semenzato): add a proper linear histogram to the Chrome external
999 // metrics API.
1000 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1001 metrics_lib_->SendEnumToUMA(name, sample, max);
1002}
Daniel Eratc83975a2014-04-04 08:53:44 -07001003
1004void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
1005 Time now_wall_time) {
1006 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
1007 daily_use_->Add(elapsed_seconds);
1008 user_crash_interval_->Add(elapsed_seconds);
1009 kernel_crash_interval_->Add(elapsed_seconds);
1010 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
1011 last_update_stats_time_ = now_ticks;
1012
1013 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
1014 const int day = since_epoch.InDays();
1015 const int week = day / 7;
1016
1017 if (daily_cycle_->Get() != day) {
1018 daily_cycle_->Set(day);
1019 SendCrashFrequencySample(any_crashes_daily_count_);
1020 SendCrashFrequencySample(user_crashes_daily_count_);
1021 SendCrashFrequencySample(kernel_crashes_daily_count_);
1022 SendCrashFrequencySample(unclean_shutdowns_daily_count_);
1023 SendKernelCrashesCumulativeCountStats(daily_use_->Get());
1024 }
1025
1026 if (weekly_cycle_->Get() != week) {
1027 weekly_cycle_->Set(week);
1028 SendCrashFrequencySample(any_crashes_weekly_count_);
1029 SendCrashFrequencySample(user_crashes_weekly_count_);
1030 SendCrashFrequencySample(kernel_crashes_weekly_count_);
1031 SendCrashFrequencySample(unclean_shutdowns_weekly_count_);
1032 }
1033}
1034
1035// static
1036gboolean MetricsDaemon::HandleUpdateStatsTimeout(gpointer data) {
1037 static_cast<MetricsDaemon*>(data)->UpdateStats(TimeTicks::Now(), Time::Now());
1038 return TRUE;
1039}