blob: 5b80b05b3067e3167ad8d93d6b99e942d27a3fe3 [file] [log] [blame]
Bertrand SIMONNET52e5b992015-08-10 15:18:00 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Darin Petkov65b01462010-04-14 13:32:20 -070016
Bertrand SIMONNET4b915ae2015-07-28 15:38:14 -070017#include "metrics_daemon.h"
Darin Petkov65b01462010-04-14 13:32:20 -070018
Steve Funge86591e2014-12-01 13:38:21 -080019#include <sysexits.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -070020#include <time.h>
Darin Petkov65b01462010-04-14 13:32:20 -070021
Bertrand SIMONNET4b915ae2015-07-28 15:38:14 -070022#include <base/bind.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080023#include <base/files/file_path.h>
Ben Chan51bf92a2014-09-05 08:21:06 -070024#include <base/files/file_util.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080025#include <base/hash.h>
Darin Petkov65b01462010-04-14 13:32:20 -070026#include <base/logging.h>
Ben Chan2e6543d2014-02-05 23:26:25 -080027#include <base/strings/string_number_conversions.h>
28#include <base/strings/string_split.h>
29#include <base/strings/string_util.h>
30#include <base/strings/stringprintf.h>
Bertrand SIMONNET26993622015-08-20 14:08:41 -070031#include <cutils/properties.h>
Steve Funge86591e2014-12-01 13:38:21 -080032#include <dbus/dbus.h>
33#include <dbus/message.h>
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -070034
35#include "constants.h"
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -070036#include "uploader/upload_service.h"
Darin Petkov65b01462010-04-14 13:32:20 -070037
Ben Chan2e6543d2014-02-05 23:26:25 -080038using base::FilePath;
39using base::StringPrintf;
Darin Petkovf27f0362010-06-04 13:14:19 -070040using base::Time;
41using base::TimeDelta;
42using base::TimeTicks;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080043using chromeos_metrics::PersistentInteger;
Bertrand SIMONNET59890e22015-10-02 16:45:18 -070044using com::android::Weave::CommandProxy;
45using com::android::Weave::ManagerProxy;
Luigi Semenzato8accd332011-05-17 16:37:18 -070046using std::map;
Darin Petkov38d5cb02010-06-24 12:10:26 -070047using std::string;
Luigi Semenzato8accd332011-05-17 16:37:18 -070048using std::vector;
49
Daniel Eratc83975a2014-04-04 08:53:44 -070050namespace {
Darin Petkovf27f0362010-06-04 13:14:19 -070051
Daniel Eratc83975a2014-04-04 08:53:44 -070052const char kCrashReporterInterface[] = "org.chromium.CrashReporter";
53const char kCrashReporterUserCrashSignal[] = "UserCrash";
Steve Funge86591e2014-12-01 13:38:21 -080054const char kCrashReporterMatchRule[] =
55 "type='signal',interface='%s',path='/',member='%s'";
Darin Petkov41e06232010-05-03 16:45:37 -070056
Daniel Eratc83975a2014-04-04 08:53:44 -070057const int kSecondsPerMinute = 60;
58const int kMinutesPerHour = 60;
59const int kHoursPerDay = 24;
60const int kMinutesPerDay = kHoursPerDay * kMinutesPerHour;
61const int kSecondsPerDay = kSecondsPerMinute * kMinutesPerDay;
62const int kDaysPerWeek = 7;
63const int kSecondsPerWeek = kSecondsPerDay * kDaysPerWeek;
Darin Petkov41e06232010-05-03 16:45:37 -070064
Daniel Eratc83975a2014-04-04 08:53:44 -070065// Interval between calls to UpdateStats().
Steve Funge86591e2014-12-01 13:38:21 -080066const uint32_t kUpdateStatsIntervalMs = 300000;
Darin Petkov65b01462010-04-14 13:32:20 -070067
Luigi Semenzatoc5a92342014-02-14 15:05:51 -080068const char kKernelCrashDetectedFile[] = "/var/run/kernel-crash-detected";
Daniel Eratc83975a2014-04-04 08:53:44 -070069const char kUncleanShutdownDetectedFile[] =
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080070 "/var/run/unclean-shutdown-detected";
Ken Mixterccd84c02010-08-16 19:57:13 -070071
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -070072const int kMetricMeminfoInterval = 30; // seconds
73
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070074const char kMetricsProcStatFileName[] = "/proc/stat";
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070075const char kMeminfoFileName[] = "/proc/meminfo";
Bertrand SIMONNET7a964052015-09-29 11:07:24 -070076const char kVmStatFileName[] = "/proc/vmstat";
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070077const int kMetricsProcStatFirstLineItemsCount = 11;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -070078
Luigi Semenzatofb3a8212013-05-07 16:55:00 -070079// Thermal CPU throttling.
80
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070081const char kMetricScaledCpuFrequencyName[] =
Luigi Semenzatofb3a8212013-05-07 16:55:00 -070082 "Platform.CpuFrequencyThermalScaling";
83
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070084} // namespace
85
Luigi Semenzato96360192014-06-04 10:53:35 -070086// Zram sysfs entries.
87
88const char MetricsDaemon::kComprDataSizeName[] = "compr_data_size";
89const char MetricsDaemon::kOrigDataSizeName[] = "orig_data_size";
90const char MetricsDaemon::kZeroPagesName[] = "zero_pages";
91
Luigi Semenzato8accd332011-05-17 16:37:18 -070092// Memory use stats collection intervals. We collect some memory use interval
93// at these intervals after boot, and we stop collecting after the last one,
94// with the assumption that in most cases the memory use won't change much
95// after that.
96static const int kMemuseIntervals[] = {
97 1 * kSecondsPerMinute, // 1 minute mark
98 4 * kSecondsPerMinute, // 5 minute mark
99 25 * kSecondsPerMinute, // 0.5 hour mark
100 120 * kSecondsPerMinute, // 2.5 hour mark
101 600 * kSecondsPerMinute, // 12.5 hour mark
102};
103
Darin Petkovf1e85e42010-06-10 15:59:53 -0700104MetricsDaemon::MetricsDaemon()
Steve Funge86591e2014-12-01 13:38:21 -0800105 : memuse_final_time_(0),
Luigi Semenzato8accd332011-05-17 16:37:18 -0700106 memuse_interval_index_(0),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700107 ticks_per_second_(0),
108 latest_cpu_use_ticks_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700109
Ken Mixter4c5daa42010-08-26 18:35:06 -0700110MetricsDaemon::~MetricsDaemon() {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700111}
112
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700113// static
Luigi Semenzato8accd332011-05-17 16:37:18 -0700114double MetricsDaemon::GetActiveTime() {
115 struct timespec ts;
116 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
117 if (r < 0) {
118 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
119 return 0;
120 } else {
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700121 return ts.tv_sec + static_cast<double>(ts.tv_nsec) / (1000 * 1000 * 1000);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700122 }
123}
124
Steve Funge86591e2014-12-01 13:38:21 -0800125int MetricsDaemon::Run() {
Ken Mixterccd84c02010-08-16 19:57:13 -0700126 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
127 ProcessKernelCrash();
128 }
129
130 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
131 ProcessUncleanShutdown();
132 }
133
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800134 // On OS version change, clear version stats (which are reported daily).
Ben Chanf05ab402014-08-07 00:54:59 -0700135 int32_t version = GetOsVersionHash();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800136 if (version_cycle_->Get() != version) {
137 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800138 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700139 version_cumulative_active_use_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700140 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800141 }
142
Steve Funge86591e2014-12-01 13:38:21 -0800143 return chromeos::DBusDaemon::Run();
Darin Petkov65b01462010-04-14 13:32:20 -0700144}
145
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700146void MetricsDaemon::RunUploaderTest() {
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700147 upload_service_.reset(new UploadService(
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700148 new SystemProfileCache(true, metrics_directory_),
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700149 metrics_lib_,
150 server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700151 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700152 upload_service_->UploadEvent();
153}
154
Ben Chanf05ab402014-08-07 00:54:59 -0700155uint32_t MetricsDaemon::GetOsVersionHash() {
156 static uint32_t cached_version_hash = 0;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800157 static bool version_hash_is_cached = false;
158 if (version_hash_is_cached)
159 return cached_version_hash;
160 version_hash_is_cached = true;
Bertrand SIMONNET26993622015-08-20 14:08:41 -0700161
162 char version[PROPERTY_VALUE_MAX];
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700163 // The version might not be set for development devices. In this case, use the
164 // zero version.
Bertrand SIMONNET26993622015-08-20 14:08:41 -0700165 property_get(metrics::kProductVersionProperty, version,
166 metrics::kDefaultVersion);
167
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700168 cached_version_hash = base::Hash(version);
169 if (testing_) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800170 cached_version_hash = 42; // return any plausible value for the hash
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800171 }
172 return cached_version_hash;
173}
174
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700175void MetricsDaemon::Init(bool testing,
176 bool uploader_active,
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700177 bool dbus_enabled,
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700178 MetricsLibraryInterface* metrics_lib,
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700179 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700180 const string& scaling_max_freq_path,
Steve Fung67906c62014-10-06 15:15:30 -0700181 const string& cpuinfo_max_freq_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700182 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700183 const string& server,
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700184 const base::FilePath& metrics_directory) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700185 CHECK(metrics_lib);
Darin Petkov65b01462010-04-14 13:32:20 -0700186 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800187 uploader_active_ = uploader_active;
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700188 dbus_enabled_ = dbus_enabled;
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700189 metrics_directory_ = metrics_directory;
Darin Petkovfc91b422010-05-12 13:05:45 -0700190 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700191
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700192 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700193 server_ = server;
Steve Fung67906c62014-10-06 15:15:30 -0700194
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700195 // Get ticks per second (HZ) on this system.
196 // Sysconf cannot fail, so no sanity checks are needed.
197 ticks_per_second_ = sysconf(_SC_CLK_TCK);
198
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700199 daily_active_use_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700200 new PersistentInteger("Platform.UseTime.PerDay"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700201 version_cumulative_active_use_.reset(
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700202 new PersistentInteger("Platform.CumulativeUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700203 version_cumulative_cpu_use_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700204 new PersistentInteger("Platform.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700205
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800206 kernel_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700207 new PersistentInteger("Platform.KernelCrashInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800208 unclean_shutdown_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700209 new PersistentInteger("Platform.UncleanShutdownInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800210 user_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700211 new PersistentInteger("Platform.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700212
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800213 any_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700214 new PersistentInteger("Platform.AnyCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800215 any_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700216 new PersistentInteger("Platform.AnyCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800217 user_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700218 new PersistentInteger("Platform.UserCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800219 user_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700220 new PersistentInteger("Platform.UserCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800221 kernel_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700222 new PersistentInteger("Platform.KernelCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800223 kernel_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700224 new PersistentInteger("Platform.KernelCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800225 kernel_crashes_version_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700226 new PersistentInteger("Platform.KernelCrashesSinceUpdate"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800227 unclean_shutdowns_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700228 new PersistentInteger("Platform.UncleanShutdown.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800229 unclean_shutdowns_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700230 new PersistentInteger("Platform.UncleanShutdowns.PerWeek"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700231
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800232 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
233 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
234 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800235
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700236 scaling_max_freq_path_ = scaling_max_freq_path;
237 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700238 disk_usage_collector_.reset(new DiskUsageCollector(metrics_lib_));
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700239 averaged_stats_collector_.reset(
240 new AveragedStatisticsCollector(metrics_lib_, diskstats_path,
241 kVmStatFileName));
Steve Funge86591e2014-12-01 13:38:21 -0800242}
243
244int MetricsDaemon::OnInit() {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700245 int return_code = dbus_enabled_ ? chromeos::DBusDaemon::OnInit() :
246 chromeos::Daemon::OnInit();
Steve Funge86591e2014-12-01 13:38:21 -0800247 if (return_code != EX_OK)
248 return return_code;
249
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700250 StatsReporterInit();
251
252 // Start collecting meminfo stats.
253 ScheduleMeminfoCallback(kMetricMeminfoInterval);
254 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
255 ScheduleMemuseCallback(kMemuseIntervals[0]);
256
Steve Funge86591e2014-12-01 13:38:21 -0800257 if (testing_)
258 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700259
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700260 if (dbus_enabled_) {
261 bus_->AssertOnDBusThread();
262 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700263
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700264 if (bus_->is_connected()) {
265 const std::string match_rule =
266 base::StringPrintf(kCrashReporterMatchRule,
267 kCrashReporterInterface,
268 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700269
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700270 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700271
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700272 DBusError error;
273 dbus_error_init(&error);
274 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700275
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700276 if (dbus_error_is_set(&error)) {
277 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
278 << error.name << ": " << error.message;
279 return EX_SOFTWARE;
280 }
281 } else {
282 LOG(ERROR) << "DBus isn't connected.";
283 return EX_UNAVAILABLE;
Steve Funge86591e2014-12-01 13:38:21 -0800284 }
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700285
286 weaved_object_mgr_.reset(new com::android::Weave::ObjectManagerProxy{bus_});
287 weaved_object_mgr_->SetCommandAddedCallback(
288 base::Bind(&MetricsDaemon::OnWeaveCommand, base::Unretained(this)));
289 weaved_object_mgr_->SetManagerAddedCallback(
290 base::Bind(&MetricsDaemon::UpdateWeaveState, base::Unretained(this)));
Darin Petkov703ec972010-04-27 11:02:18 -0700291 }
292
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700293 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
294 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
295 base::Unretained(this)),
296 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
297
Steve Funge86591e2014-12-01 13:38:21 -0800298 if (uploader_active_) {
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700299 upload_service_.reset(
300 new UploadService(new SystemProfileCache(), metrics_lib_, server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700301 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700302 }
Steve Funge86591e2014-12-01 13:38:21 -0800303
304 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700305}
306
Steve Funge86591e2014-12-01 13:38:21 -0800307void MetricsDaemon::OnShutdown(int* return_code) {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700308 if (!testing_ && dbus_enabled_ && bus_->is_connected()) {
Steve Funge86591e2014-12-01 13:38:21 -0800309 const std::string match_rule =
310 base::StringPrintf(kCrashReporterMatchRule,
311 kCrashReporterInterface,
312 kCrashReporterUserCrashSignal);
313
314 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
315
316 DBusError error;
317 dbus_error_init(&error);
318 bus_->RemoveMatch(match_rule, &error);
319
320 if (dbus_error_is_set(&error)) {
321 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
322 << error.name << ": " << error.message;
323 }
324 }
325 chromeos::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700326}
327
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700328void MetricsDaemon::OnWeaveCommand(CommandProxy* command) {
329 if (command->category() != "metrics" || command->status() != "queued") {
330 return;
331 }
332
333 VLOG(1) << "received weave command: " << command->name();
334 if (command->name() == "_metrics._enableAnalyticsReporting") {
335 OnEnableMetrics(command);
336 } else if (command->name() == "_metrics._disableAnalyticsReporting") {
337 OnDisableMetrics(command);
338 }
339}
340
341void MetricsDaemon::OnEnableMetrics(CommandProxy* command) {
342 if (base::WriteFile(metrics_directory_.Append(metrics::kConsentFileName),
343 "", 0) != 0) {
344 PLOG(ERROR) << "Could not create the consent file.";
345 command->Abort(nullptr);
346 return;
347 }
348
349 NotifyStateChanged();
350 command->Done(nullptr);
351}
352
353void MetricsDaemon::OnDisableMetrics(CommandProxy* command) {
354 if (!base::DeleteFile(metrics_directory_.Append(metrics::kConsentFileName),
355 false)) {
356 PLOG(ERROR) << "Cound not delete the consent file.";
357 command->Abort(nullptr);
358 return;
359 }
360
361 NotifyStateChanged();
362 command->Done(nullptr);
363}
364
365void MetricsDaemon::NotifyStateChanged() {
366 ManagerProxy* manager = weaved_object_mgr_->GetManagerProxy();
367 if (manager)
368 UpdateWeaveState(manager);
369}
370
371void MetricsDaemon::UpdateWeaveState(ManagerProxy* manager) {
372 chromeos::VariantDictionary state_change{
373 { "_metrics._AnalyticsReportingState",
374 metrics_lib_->AreMetricsEnabled() ? "enabled" : "disabled" }
375 };
376
377 if (!manager->UpdateState(state_change, nullptr)) {
378 LOG(ERROR) << "failed to update weave's state";
379 }
380}
381
Darin Petkov703ec972010-04-27 11:02:18 -0700382// static
383DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
384 DBusMessage* message,
385 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700386 int message_type = dbus_message_get_type(message);
387 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700388 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700389 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
390 }
391
392 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700393 const std::string interface(dbus_message_get_interface(message));
394 const std::string member(dbus_message_get_member(message));
395 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700396
397 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
398
399 DBusMessageIter iter;
400 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700401 if (interface == kCrashReporterInterface) {
402 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700403 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700404 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700405 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700406 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
407 }
408
409 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700410}
411
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700412// One might argue that parts of this should go into
413// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
414
415TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700416 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
417 std::string proc_stat_string;
418 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
419 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
420 return TimeDelta();
421 }
422
423 std::vector<std::string> proc_stat_lines;
424 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
425 if (proc_stat_lines.empty()) {
426 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
427 << ": " << proc_stat_string;
428 return TimeDelta();
429 }
430 std::vector<std::string> proc_stat_totals;
431 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
432
Ben Chanf05ab402014-08-07 00:54:59 -0700433 uint64_t user_ticks, user_nice_ticks, system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700434 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
435 proc_stat_totals[0] != "cpu" ||
436 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
437 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
438 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
439 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
440 return TimeDelta(base::TimeDelta::FromSeconds(0));
441 }
442
Ben Chanf05ab402014-08-07 00:54:59 -0700443 uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700444
445 // Sanity check.
446 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
447 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
448 << " to " << total_cpu_use_ticks;
449 return TimeDelta();
450 }
451
Ben Chanf05ab402014-08-07 00:54:59 -0700452 uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700453 latest_cpu_use_ticks_ = total_cpu_use_ticks;
454 // Use microseconds to avoid significant truncations.
455 return base::TimeDelta::FromMicroseconds(
456 diff * 1000 * 1000 / ticks_per_second_);
457}
458
Darin Petkov1bb904e2010-06-16 15:58:06 -0700459void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700460 // Counts the active time up to now.
461 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700462
463 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700464 SendAndResetCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700465
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800466 any_crashes_daily_count_->Add(1);
467 any_crashes_weekly_count_->Add(1);
468 user_crashes_daily_count_->Add(1);
469 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700470}
471
Darin Petkov38d5cb02010-06-24 12:10:26 -0700472void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700473 // Counts the active time up to now.
474 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700475
476 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700477 SendAndResetCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700478
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800479 any_crashes_daily_count_->Add(1);
480 any_crashes_weekly_count_->Add(1);
481 kernel_crashes_daily_count_->Add(1);
482 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800483
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800484 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700485}
486
Ken Mixterccd84c02010-08-16 19:57:13 -0700487void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700488 // Counts the active time up to now.
489 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700490
491 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700492 SendAndResetCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700493
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800494 unclean_shutdowns_daily_count_->Add(1);
495 unclean_shutdowns_weekly_count_->Add(1);
496 any_crashes_daily_count_->Add(1);
497 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700498}
499
Luigi Semenzato8accd332011-05-17 16:37:18 -0700500bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700501 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800502 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700503 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700504
505 // Deletes the crash-detected file so that the daemon doesn't report
506 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800507 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700508 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700509}
510
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700511void MetricsDaemon::StatsReporterInit() {
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700512 disk_usage_collector_->Schedule();
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700513
514 // Don't start a collection cycle during the first run to avoid delaying the
515 // boot.
516 averaged_stats_collector_->ScheduleWait();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800517}
518
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800519
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700520bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700521 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700522 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800523 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700524 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
525 return false;
526 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800527 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700528 LOG(WARNING) << "no newline in " << value_string;
529 // Continue even though the lack of newline is suspicious.
530 }
531 if (!base::StringToInt(value_string, value)) {
532 LOG(WARNING) << "cannot convert " << value_string << " to int";
533 return false;
534 }
535 return true;
536}
537
538void MetricsDaemon::SendCpuThrottleMetrics() {
539 // |max_freq| is 0 only the first time through.
540 static int max_freq = 0;
541 if (max_freq == -1)
542 // Give up, as sysfs did not report max_freq correctly.
543 return;
544 if (max_freq == 0 || testing_) {
545 // One-time initialization of max_freq. (Every time when testing.)
546 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
547 max_freq = -1;
548 return;
549 }
550 if (max_freq == 0) {
551 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
552 max_freq = -1;
553 return;
554 }
555 if (max_freq % 10000 == 1000) {
556 // Special case: system has turbo mode, and max non-turbo frequency is
557 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
558 // being multiples of (at least) 10 MHz. Although there is no guarantee
559 // of this, it seems a fairly reasonable assumption. Otherwise we should
560 // read scaling_available_frequencies, sort the frequencies, compare the
561 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
562 // hack too, no telling when it will change).
563 max_freq -= 1000;
564 }
565 }
566 int scaled_freq = 0;
567 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
568 return;
569 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
570 // scaled_freq is not the actual turbo frequency. We indicate this situation
571 // with a 101% value.
572 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800573 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700574}
575
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700576void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
577 if (testing_) {
578 return;
579 }
Steve Funge86591e2014-12-01 13:38:21 -0800580 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
581 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
582 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800583 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800584 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700585}
586
Steve Funge86591e2014-12-01 13:38:21 -0800587void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700588 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700589 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800590 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700591 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800592 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700593 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700594 // Make both calls even if the first one fails.
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700595 if (ProcessMeminfo(meminfo_raw)) {
Steve Funge86591e2014-12-01 13:38:21 -0800596 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
597 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800598 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800599 wait);
600 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700601}
602
603// static
604bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700605 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700606 std::string content;
607 if (!base::ReadFileToString(path, &content)) {
608 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
609 return false;
610 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700611 // Remove final newline.
612 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700613 if (!base::StringToUint64(content, value)) {
614 LOG(WARNING) << "invalid integer: " << content;
615 return false;
616 }
617 return true;
618}
619
620bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
621 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700622 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700623 const size_t page_size = 4096;
624
625 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
626 &compr_data_size) ||
627 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
628 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
629 return false;
630 }
631
632 // |orig_data_size| does not include zero-filled pages.
633 orig_data_size += zero_pages * page_size;
634
635 const int compr_data_size_mb = compr_data_size >> 20;
636 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
637 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
638
639 // Report compressed size in megabytes. 100 MB or less has little impact.
640 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
641 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
642 // The compression ratio is multiplied by 100 for better resolution. The
643 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
644 // don't want samples when very little memory is being compressed.
645 if (compr_data_size_mb >= 1) {
646 SendSample("Platform.ZramCompressionRatioPercent",
647 orig_data_size * 100 / compr_data_size, 100, 600, 50);
648 }
649 // The values of interest for zero_pages are between 1MB and 1GB. The units
650 // are number of pages.
651 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
652 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
653
654 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700655}
656
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700657bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700658 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700659 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
660 { "MemFree", "MemFree" },
661 { "Buffers", "Buffers" },
662 { "Cached", "Cached" },
663 // { "SwapCached", "SwapCached" },
664 { "Active", "Active" },
665 { "Inactive", "Inactive" },
666 { "ActiveAnon", "Active(anon)" },
667 { "InactiveAnon", "Inactive(anon)" },
668 { "ActiveFile" , "Active(file)" },
669 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800670 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700671 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800672 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
673 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700674 // { "Dirty", "Dirty" },
675 // { "Writeback", "Writeback" },
676 { "AnonPages", "AnonPages" },
677 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800678 { "Shmem", "Shmem", kMeminfoOp_HistLog },
679 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700680 // { "SReclaimable", "SReclaimable" },
681 // { "SUnreclaim", "SUnreclaim" },
682 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700683 vector<MeminfoRecord> fields(fields_array,
684 fields_array + arraysize(fields_array));
685 if (!FillMeminfo(meminfo_raw, &fields)) {
686 return false;
687 }
688 int total_memory = fields[0].value;
689 if (total_memory == 0) {
690 // this "cannot happen"
691 LOG(WARNING) << "borked meminfo parser";
692 return false;
693 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800694 int swap_total = 0;
695 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700696 // Send all fields retrieved, except total memory.
697 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800698 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
699 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800700 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800701 switch (fields[i].op) {
702 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800703 // report value as percent of total memory
704 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800705 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800706 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800707 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800708 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800709 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800710 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800711 case kMeminfoOp_SwapTotal:
712 swap_total = fields[i].value;
713 case kMeminfoOp_SwapFree:
714 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800715 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700716 }
717 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800718 if (swap_total > 0) {
719 int swap_used = swap_total - swap_free;
720 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800721 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -0700722 SendLinearSample("Platform.MeminfoSwapUsed.Percent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800723 100, 101);
724 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700725 return true;
726}
727
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700728bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
729 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700730 vector<string> lines;
731 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700732
733 // Scan meminfo output and collect field values. Each field name has to
734 // match a meminfo entry (case insensitive) after removing non-alpha
735 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700736 unsigned int ifield = 0;
737 for (unsigned int iline = 0;
738 iline < nlines && ifield < fields->size();
739 iline++) {
740 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700741 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700742 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
743 // Name matches. Parse value and save.
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700744 if (!base::StringToInt(tokens[1], &(*fields)[ifield].value)) {
745 LOG(WARNING) << "Cound not convert " << tokens[1] << " to int";
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700746 return false;
747 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700748 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700749 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700750 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700751 if (ifield < fields->size()) {
752 // End of input reached while scanning.
753 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
754 << " and following";
755 return false;
756 }
757 return true;
758}
759
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800760void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700761 if (testing_) {
762 return;
763 }
Steve Funge86591e2014-12-01 13:38:21 -0800764 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
765 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
766 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700767}
768
769void MetricsDaemon::MemuseCallback() {
770 // Since we only care about active time (i.e. uptime minus sleep time) but
771 // the callbacks are driven by real time (uptime), we check if we should
772 // reschedule this callback due to intervening sleep periods.
773 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800774 // Avoid intervals of less than one second.
775 double remaining_time = ceil(memuse_final_time_ - now);
776 if (remaining_time > 0) {
777 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700778 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800779 // Report stats and advance the measurement interval unless there are
780 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700781 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800782 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
783 double interval = kMemuseIntervals[memuse_interval_index_++];
784 memuse_final_time_ = now + interval;
785 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700786 }
787 }
788}
789
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700790bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700791 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700792 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800793 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700794 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
795 return false;
796 }
797 return ProcessMemuse(meminfo_raw);
798}
799
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700800bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700801 static const MeminfoRecord fields_array[] = {
802 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
803 { "ActiveAnon", "Active(anon)" },
804 { "InactiveAnon", "Inactive(anon)" },
805 };
806 vector<MeminfoRecord> fields(fields_array,
807 fields_array + arraysize(fields_array));
808 if (!FillMeminfo(meminfo_raw, &fields)) {
809 return false;
810 }
811 int total = fields[0].value;
812 int active_anon = fields[1].value;
813 int inactive_anon = fields[2].value;
814 if (total == 0) {
815 // this "cannot happen"
816 LOG(WARNING) << "borked meminfo parser";
817 return false;
818 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800819 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
820 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800821 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -0700822 100, 101);
823 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700824}
825
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800826void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -0700827 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -0700828 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700829}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700830
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700831void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800832 // Report the number of crashes for this OS version, but don't clear the
833 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -0700834 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800835 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700836 crashes_count,
837 1, // value of first bucket
838 500, // value of last bucket
839 100); // number of buckets
840
841
Ben Chanf05ab402014-08-07 00:54:59 -0700842 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700843 SendSample(version_cumulative_cpu_use_->Name(),
844 cpu_use_ms / 1000, // stat is in seconds
845 1, // device may be used very little...
846 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
847 100);
848
849 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
850 // can be zero. Avoid division by zero.
851 if (cpu_use_ms > 0) {
852 // Send the crash frequency since update in number of crashes per CPU year.
853 SendSample("Logging.KernelCrashesPerCpuYear",
854 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
855 1,
856 1000 * 1000, // about one crash every 30s of CPU time
857 100);
858 }
859
Ben Chanf05ab402014-08-07 00:54:59 -0700860 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700861 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700862 SendSample(version_cumulative_active_use_->Name(),
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700863 active_use_seconds,
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700864 1, // device may be used very little...
865 8 * 1000 * 1000, // ... or a lot (about 90 days)
866 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700867 // Same as above, but per year of active time.
868 SendSample("Logging.KernelCrashesPerActiveYear",
869 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
870 1,
871 1000 * 1000, // about one crash every 30s of active time
872 100);
873 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800874}
875
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700876void MetricsDaemon::SendAndResetDailyUseSample(
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700877 const scoped_ptr<PersistentInteger>& use) {
878 SendSample(use->Name(),
879 use->GetAndClear(),
880 1, // value of first bucket
881 kSecondsPerDay, // value of last bucket
882 50); // number of buckets
883}
884
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700885void MetricsDaemon::SendAndResetCrashIntervalSample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800886 const scoped_ptr<PersistentInteger>& interval) {
887 SendSample(interval->Name(),
888 interval->GetAndClear(),
889 1, // value of first bucket
890 4 * kSecondsPerWeek, // value of last bucket
891 50); // number of buckets
892}
893
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700894void MetricsDaemon::SendAndResetCrashFrequencySample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800895 const scoped_ptr<PersistentInteger>& frequency) {
896 SendSample(frequency->Name(),
897 frequency->GetAndClear(),
898 1, // value of first bucket
899 100, // value of last bucket
900 50); // number of buckets
901}
902
903void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700904 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700905 // TODO(semenzato): add a proper linear histogram to the Chrome external
906 // metrics API.
907 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
908 metrics_lib_->SendEnumToUMA(name, sample, max);
909}
Daniel Eratc83975a2014-04-04 08:53:44 -0700910
911void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
912 Time now_wall_time) {
913 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700914 daily_active_use_->Add(elapsed_seconds);
915 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -0700916 user_crash_interval_->Add(elapsed_seconds);
917 kernel_crash_interval_->Add(elapsed_seconds);
918 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
919 last_update_stats_time_ = now_ticks;
920
921 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
922 const int day = since_epoch.InDays();
923 const int week = day / 7;
924
925 if (daily_cycle_->Get() != day) {
926 daily_cycle_->Set(day);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700927 SendAndResetDailyUseSample(daily_active_use_);
928 SendAndResetCrashFrequencySample(any_crashes_daily_count_);
929 SendAndResetCrashFrequencySample(user_crashes_daily_count_);
930 SendAndResetCrashFrequencySample(kernel_crashes_daily_count_);
931 SendAndResetCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700932 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -0700933 }
934
935 if (weekly_cycle_->Get() != week) {
936 weekly_cycle_->Set(week);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700937 SendAndResetCrashFrequencySample(any_crashes_weekly_count_);
938 SendAndResetCrashFrequencySample(user_crashes_weekly_count_);
939 SendAndResetCrashFrequencySample(kernel_crashes_weekly_count_);
940 SendAndResetCrashFrequencySample(unclean_shutdowns_weekly_count_);
Daniel Eratc83975a2014-04-04 08:53:44 -0700941 }
942}
943
Steve Funge86591e2014-12-01 13:38:21 -0800944void MetricsDaemon::HandleUpdateStatsTimeout() {
945 UpdateStats(TimeTicks::Now(), Time::Now());
946 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
947 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
948 base::Unretained(this)),
949 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -0700950}