blob: ed786e1fb325f5f009b7b88c3091a413512ddd34 [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 SIMONNETeb697ab2015-10-14 13:26:42 -070031#include <brillo/osrelease_reader.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
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700143 return brillo::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() {
Bertrand SIMONNETeb697ab2015-10-14 13:26:42 -0700156 brillo::OsReleaseReader reader;
157 reader.Load();
158 string version;
159 if (!reader.GetString(metrics::kProductVersion, &version)) {
160 LOG(ERROR) << "failed to read the product version.";
161 version = metrics::kDefaultVersion;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800162 }
Bertrand SIMONNETeb697ab2015-10-14 13:26:42 -0700163
164 uint32_t version_hash = base::Hash(version);
165 if (testing_) {
166 version_hash = 42; // return any plausible value for the hash
167 }
168 return version_hash;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800169}
170
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700171void MetricsDaemon::Init(bool testing,
172 bool uploader_active,
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700173 bool dbus_enabled,
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700174 MetricsLibraryInterface* metrics_lib,
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700175 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700176 const string& scaling_max_freq_path,
Steve Fung67906c62014-10-06 15:15:30 -0700177 const string& cpuinfo_max_freq_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700178 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700179 const string& server,
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700180 const base::FilePath& metrics_directory) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700181 CHECK(metrics_lib);
Darin Petkov65b01462010-04-14 13:32:20 -0700182 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800183 uploader_active_ = uploader_active;
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700184 dbus_enabled_ = dbus_enabled;
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700185 metrics_directory_ = metrics_directory;
Darin Petkovfc91b422010-05-12 13:05:45 -0700186 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700187
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700188 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700189 server_ = server;
Steve Fung67906c62014-10-06 15:15:30 -0700190
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700191 // Get ticks per second (HZ) on this system.
192 // Sysconf cannot fail, so no sanity checks are needed.
193 ticks_per_second_ = sysconf(_SC_CLK_TCK);
194
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700195 daily_active_use_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700196 new PersistentInteger("Platform.UseTime.PerDay"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700197 version_cumulative_active_use_.reset(
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700198 new PersistentInteger("Platform.CumulativeUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700199 version_cumulative_cpu_use_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700200 new PersistentInteger("Platform.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700201
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800202 kernel_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700203 new PersistentInteger("Platform.KernelCrashInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800204 unclean_shutdown_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700205 new PersistentInteger("Platform.UncleanShutdownInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800206 user_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700207 new PersistentInteger("Platform.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700208
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800209 any_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700210 new PersistentInteger("Platform.AnyCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800211 any_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700212 new PersistentInteger("Platform.AnyCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800213 user_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700214 new PersistentInteger("Platform.UserCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800215 user_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700216 new PersistentInteger("Platform.UserCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800217 kernel_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700218 new PersistentInteger("Platform.KernelCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800219 kernel_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700220 new PersistentInteger("Platform.KernelCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800221 kernel_crashes_version_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700222 new PersistentInteger("Platform.KernelCrashesSinceUpdate"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800223 unclean_shutdowns_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700224 new PersistentInteger("Platform.UncleanShutdown.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800225 unclean_shutdowns_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700226 new PersistentInteger("Platform.UncleanShutdowns.PerWeek"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700227
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800228 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
229 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
230 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800231
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700232 scaling_max_freq_path_ = scaling_max_freq_path;
233 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700234 disk_usage_collector_.reset(new DiskUsageCollector(metrics_lib_));
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700235 averaged_stats_collector_.reset(
236 new AveragedStatisticsCollector(metrics_lib_, diskstats_path,
237 kVmStatFileName));
Steve Funge86591e2014-12-01 13:38:21 -0800238}
239
240int MetricsDaemon::OnInit() {
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700241 int return_code = dbus_enabled_ ? brillo::DBusDaemon::OnInit() :
242 brillo::Daemon::OnInit();
Steve Funge86591e2014-12-01 13:38:21 -0800243 if (return_code != EX_OK)
244 return return_code;
245
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700246 StatsReporterInit();
247
248 // Start collecting meminfo stats.
249 ScheduleMeminfoCallback(kMetricMeminfoInterval);
250 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
251 ScheduleMemuseCallback(kMemuseIntervals[0]);
252
Steve Funge86591e2014-12-01 13:38:21 -0800253 if (testing_)
254 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700255
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700256 if (dbus_enabled_) {
257 bus_->AssertOnDBusThread();
258 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700259
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700260 if (bus_->is_connected()) {
261 const std::string match_rule =
262 base::StringPrintf(kCrashReporterMatchRule,
263 kCrashReporterInterface,
264 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700265
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700266 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700267
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700268 DBusError error;
269 dbus_error_init(&error);
270 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700271
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700272 if (dbus_error_is_set(&error)) {
273 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
274 << error.name << ": " << error.message;
275 return EX_SOFTWARE;
276 }
277 } else {
278 LOG(ERROR) << "DBus isn't connected.";
279 return EX_UNAVAILABLE;
Steve Funge86591e2014-12-01 13:38:21 -0800280 }
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700281
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700282 device_ = weaved::Device::CreateInstance(
283 bus_,
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700284 base::Bind(&MetricsDaemon::UpdateWeaveState, base::Unretained(this)));
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700285 device_->AddCommandHandler(
286 "_metrics._enableAnalyticsReporting",
287 base::Bind(&MetricsDaemon::OnEnableMetrics, base::Unretained(this)));
288 device_->AddCommandHandler(
289 "_metrics._disableAnalyticsReporting",
290 base::Bind(&MetricsDaemon::OnDisableMetrics, 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 }
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700325 brillo::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700326}
327
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700328void MetricsDaemon::OnEnableMetrics(const std::weak_ptr<weaved::Command>& cmd) {
329 auto command = cmd.lock();
330 if (!command)
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700331 return;
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700332
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700333 if (base::WriteFile(metrics_directory_.Append(metrics::kConsentFileName),
334 "", 0) != 0) {
335 PLOG(ERROR) << "Could not create the consent file.";
Alex Vakulenko35f89632015-10-09 08:18:35 -0700336 command->Abort("metrics_error", "Could not create the consent file",
337 nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700338 return;
339 }
340
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700341 UpdateWeaveState();
Alex Vakulenko35f89632015-10-09 08:18:35 -0700342 command->Complete({}, nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700343}
344
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700345void MetricsDaemon::OnDisableMetrics(
346 const std::weak_ptr<weaved::Command>& cmd) {
347 auto command = cmd.lock();
348 if (!command)
349 return;
350
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700351 if (!base::DeleteFile(metrics_directory_.Append(metrics::kConsentFileName),
352 false)) {
Alex Vakulenko35f89632015-10-09 08:18:35 -0700353 PLOG(ERROR) << "Could not delete the consent file.";
354 command->Abort("metrics_error", "Could not delete the consent file",
355 nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700356 return;
357 }
358
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700359 UpdateWeaveState();
Alex Vakulenko35f89632015-10-09 08:18:35 -0700360 command->Complete({}, nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700361}
362
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700363void MetricsDaemon::UpdateWeaveState() {
364 if (!device_)
365 return;
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700366
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700367 brillo::VariantDictionary state_change{
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700368 { "_metrics._AnalyticsReportingState",
369 metrics_lib_->AreMetricsEnabled() ? "enabled" : "disabled" }
370 };
371
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700372 if (!device_->SetStateProperties(state_change, nullptr)) {
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700373 LOG(ERROR) << "failed to update weave's state";
374 }
375}
376
Darin Petkov703ec972010-04-27 11:02:18 -0700377// static
378DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
379 DBusMessage* message,
380 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700381 int message_type = dbus_message_get_type(message);
382 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700383 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700384 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
385 }
386
387 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700388 const std::string interface(dbus_message_get_interface(message));
389 const std::string member(dbus_message_get_member(message));
390 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700391
392 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
393
394 DBusMessageIter iter;
395 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700396 if (interface == kCrashReporterInterface) {
397 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700398 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700399 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700400 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700401 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
402 }
403
404 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700405}
406
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700407// One might argue that parts of this should go into
408// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
409
410TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700411 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
412 std::string proc_stat_string;
413 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
414 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
415 return TimeDelta();
416 }
417
418 std::vector<std::string> proc_stat_lines;
419 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
420 if (proc_stat_lines.empty()) {
421 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
422 << ": " << proc_stat_string;
423 return TimeDelta();
424 }
425 std::vector<std::string> proc_stat_totals;
426 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
427
Ben Chanf05ab402014-08-07 00:54:59 -0700428 uint64_t user_ticks, user_nice_ticks, system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700429 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
430 proc_stat_totals[0] != "cpu" ||
431 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
432 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
433 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
434 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
435 return TimeDelta(base::TimeDelta::FromSeconds(0));
436 }
437
Ben Chanf05ab402014-08-07 00:54:59 -0700438 uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700439
440 // Sanity check.
441 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
442 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
443 << " to " << total_cpu_use_ticks;
444 return TimeDelta();
445 }
446
Ben Chanf05ab402014-08-07 00:54:59 -0700447 uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700448 latest_cpu_use_ticks_ = total_cpu_use_ticks;
449 // Use microseconds to avoid significant truncations.
450 return base::TimeDelta::FromMicroseconds(
451 diff * 1000 * 1000 / ticks_per_second_);
452}
453
Darin Petkov1bb904e2010-06-16 15:58:06 -0700454void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700455 // Counts the active time up to now.
456 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700457
458 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700459 SendAndResetCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700460
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800461 any_crashes_daily_count_->Add(1);
462 any_crashes_weekly_count_->Add(1);
463 user_crashes_daily_count_->Add(1);
464 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700465}
466
Darin Petkov38d5cb02010-06-24 12:10:26 -0700467void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700468 // Counts the active time up to now.
469 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700470
471 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700472 SendAndResetCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700473
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800474 any_crashes_daily_count_->Add(1);
475 any_crashes_weekly_count_->Add(1);
476 kernel_crashes_daily_count_->Add(1);
477 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800478
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800479 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700480}
481
Ken Mixterccd84c02010-08-16 19:57:13 -0700482void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700483 // Counts the active time up to now.
484 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700485
486 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700487 SendAndResetCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700488
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800489 unclean_shutdowns_daily_count_->Add(1);
490 unclean_shutdowns_weekly_count_->Add(1);
491 any_crashes_daily_count_->Add(1);
492 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700493}
494
Luigi Semenzato8accd332011-05-17 16:37:18 -0700495bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700496 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800497 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700498 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700499
500 // Deletes the crash-detected file so that the daemon doesn't report
501 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800502 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700503 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700504}
505
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700506void MetricsDaemon::StatsReporterInit() {
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700507 disk_usage_collector_->Schedule();
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700508
509 // Don't start a collection cycle during the first run to avoid delaying the
510 // boot.
511 averaged_stats_collector_->ScheduleWait();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800512}
513
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800514
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700515bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700516 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700517 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800518 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700519 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
520 return false;
521 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800522 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700523 LOG(WARNING) << "no newline in " << value_string;
524 // Continue even though the lack of newline is suspicious.
525 }
526 if (!base::StringToInt(value_string, value)) {
527 LOG(WARNING) << "cannot convert " << value_string << " to int";
528 return false;
529 }
530 return true;
531}
532
533void MetricsDaemon::SendCpuThrottleMetrics() {
534 // |max_freq| is 0 only the first time through.
535 static int max_freq = 0;
536 if (max_freq == -1)
537 // Give up, as sysfs did not report max_freq correctly.
538 return;
539 if (max_freq == 0 || testing_) {
540 // One-time initialization of max_freq. (Every time when testing.)
541 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
542 max_freq = -1;
543 return;
544 }
545 if (max_freq == 0) {
546 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
547 max_freq = -1;
548 return;
549 }
550 if (max_freq % 10000 == 1000) {
551 // Special case: system has turbo mode, and max non-turbo frequency is
552 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
553 // being multiples of (at least) 10 MHz. Although there is no guarantee
554 // of this, it seems a fairly reasonable assumption. Otherwise we should
555 // read scaling_available_frequencies, sort the frequencies, compare the
556 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
557 // hack too, no telling when it will change).
558 max_freq -= 1000;
559 }
560 }
561 int scaled_freq = 0;
562 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
563 return;
564 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
565 // scaled_freq is not the actual turbo frequency. We indicate this situation
566 // with a 101% value.
567 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800568 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700569}
570
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700571void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
572 if (testing_) {
573 return;
574 }
Steve Funge86591e2014-12-01 13:38:21 -0800575 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
576 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
577 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800578 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800579 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700580}
581
Steve Funge86591e2014-12-01 13:38:21 -0800582void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700583 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700584 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800585 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700586 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800587 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700588 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700589 // Make both calls even if the first one fails.
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700590 if (ProcessMeminfo(meminfo_raw)) {
Steve Funge86591e2014-12-01 13:38:21 -0800591 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
592 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800593 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800594 wait);
595 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700596}
597
598// static
599bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700600 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700601 std::string content;
602 if (!base::ReadFileToString(path, &content)) {
603 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
604 return false;
605 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700606 // Remove final newline.
607 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700608 if (!base::StringToUint64(content, value)) {
609 LOG(WARNING) << "invalid integer: " << content;
610 return false;
611 }
612 return true;
613}
614
615bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
616 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700617 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700618 const size_t page_size = 4096;
619
620 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
621 &compr_data_size) ||
622 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
623 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
624 return false;
625 }
626
627 // |orig_data_size| does not include zero-filled pages.
628 orig_data_size += zero_pages * page_size;
629
630 const int compr_data_size_mb = compr_data_size >> 20;
631 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
632 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
633
634 // Report compressed size in megabytes. 100 MB or less has little impact.
635 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
636 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
637 // The compression ratio is multiplied by 100 for better resolution. The
638 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
639 // don't want samples when very little memory is being compressed.
640 if (compr_data_size_mb >= 1) {
641 SendSample("Platform.ZramCompressionRatioPercent",
642 orig_data_size * 100 / compr_data_size, 100, 600, 50);
643 }
644 // The values of interest for zero_pages are between 1MB and 1GB. The units
645 // are number of pages.
646 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
647 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
648
649 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700650}
651
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700652bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700653 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700654 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
655 { "MemFree", "MemFree" },
656 { "Buffers", "Buffers" },
657 { "Cached", "Cached" },
658 // { "SwapCached", "SwapCached" },
659 { "Active", "Active" },
660 { "Inactive", "Inactive" },
661 { "ActiveAnon", "Active(anon)" },
662 { "InactiveAnon", "Inactive(anon)" },
663 { "ActiveFile" , "Active(file)" },
664 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800665 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700666 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800667 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
668 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700669 // { "Dirty", "Dirty" },
670 // { "Writeback", "Writeback" },
671 { "AnonPages", "AnonPages" },
672 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800673 { "Shmem", "Shmem", kMeminfoOp_HistLog },
674 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700675 // { "SReclaimable", "SReclaimable" },
676 // { "SUnreclaim", "SUnreclaim" },
677 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700678 vector<MeminfoRecord> fields(fields_array,
679 fields_array + arraysize(fields_array));
680 if (!FillMeminfo(meminfo_raw, &fields)) {
681 return false;
682 }
683 int total_memory = fields[0].value;
684 if (total_memory == 0) {
685 // this "cannot happen"
686 LOG(WARNING) << "borked meminfo parser";
687 return false;
688 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800689 int swap_total = 0;
690 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700691 // Send all fields retrieved, except total memory.
692 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800693 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
694 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800695 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800696 switch (fields[i].op) {
697 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800698 // report value as percent of total memory
699 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800700 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800701 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800702 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800703 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800704 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800705 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800706 case kMeminfoOp_SwapTotal:
707 swap_total = fields[i].value;
708 case kMeminfoOp_SwapFree:
709 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800710 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700711 }
712 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800713 if (swap_total > 0) {
714 int swap_used = swap_total - swap_free;
715 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800716 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -0700717 SendLinearSample("Platform.MeminfoSwapUsed.Percent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800718 100, 101);
719 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700720 return true;
721}
722
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700723bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
724 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700725 vector<string> lines;
726 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700727
728 // Scan meminfo output and collect field values. Each field name has to
729 // match a meminfo entry (case insensitive) after removing non-alpha
730 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700731 unsigned int ifield = 0;
732 for (unsigned int iline = 0;
733 iline < nlines && ifield < fields->size();
734 iline++) {
735 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700736 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700737 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
738 // Name matches. Parse value and save.
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700739 if (!base::StringToInt(tokens[1], &(*fields)[ifield].value)) {
740 LOG(WARNING) << "Cound not convert " << tokens[1] << " to int";
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700741 return false;
742 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700743 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700744 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700745 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700746 if (ifield < fields->size()) {
747 // End of input reached while scanning.
748 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
749 << " and following";
750 return false;
751 }
752 return true;
753}
754
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800755void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700756 if (testing_) {
757 return;
758 }
Steve Funge86591e2014-12-01 13:38:21 -0800759 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
760 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
761 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700762}
763
764void MetricsDaemon::MemuseCallback() {
765 // Since we only care about active time (i.e. uptime minus sleep time) but
766 // the callbacks are driven by real time (uptime), we check if we should
767 // reschedule this callback due to intervening sleep periods.
768 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800769 // Avoid intervals of less than one second.
770 double remaining_time = ceil(memuse_final_time_ - now);
771 if (remaining_time > 0) {
772 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700773 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800774 // Report stats and advance the measurement interval unless there are
775 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700776 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800777 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
778 double interval = kMemuseIntervals[memuse_interval_index_++];
779 memuse_final_time_ = now + interval;
780 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700781 }
782 }
783}
784
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700785bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700786 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700787 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800788 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700789 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
790 return false;
791 }
792 return ProcessMemuse(meminfo_raw);
793}
794
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700795bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700796 static const MeminfoRecord fields_array[] = {
797 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
798 { "ActiveAnon", "Active(anon)" },
799 { "InactiveAnon", "Inactive(anon)" },
800 };
801 vector<MeminfoRecord> fields(fields_array,
802 fields_array + arraysize(fields_array));
803 if (!FillMeminfo(meminfo_raw, &fields)) {
804 return false;
805 }
806 int total = fields[0].value;
807 int active_anon = fields[1].value;
808 int inactive_anon = fields[2].value;
809 if (total == 0) {
810 // this "cannot happen"
811 LOG(WARNING) << "borked meminfo parser";
812 return false;
813 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800814 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
815 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800816 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -0700817 100, 101);
818 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700819}
820
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800821void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -0700822 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -0700823 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700824}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700825
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700826void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800827 // Report the number of crashes for this OS version, but don't clear the
828 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -0700829 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800830 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700831 crashes_count,
832 1, // value of first bucket
833 500, // value of last bucket
834 100); // number of buckets
835
836
Ben Chanf05ab402014-08-07 00:54:59 -0700837 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700838 SendSample(version_cumulative_cpu_use_->Name(),
839 cpu_use_ms / 1000, // stat is in seconds
840 1, // device may be used very little...
841 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
842 100);
843
844 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
845 // can be zero. Avoid division by zero.
846 if (cpu_use_ms > 0) {
847 // Send the crash frequency since update in number of crashes per CPU year.
848 SendSample("Logging.KernelCrashesPerCpuYear",
849 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
850 1,
851 1000 * 1000, // about one crash every 30s of CPU time
852 100);
853 }
854
Ben Chanf05ab402014-08-07 00:54:59 -0700855 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700856 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700857 SendSample(version_cumulative_active_use_->Name(),
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700858 active_use_seconds,
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700859 1, // device may be used very little...
860 8 * 1000 * 1000, // ... or a lot (about 90 days)
861 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700862 // Same as above, but per year of active time.
863 SendSample("Logging.KernelCrashesPerActiveYear",
864 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
865 1,
866 1000 * 1000, // about one crash every 30s of active time
867 100);
868 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800869}
870
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700871void MetricsDaemon::SendAndResetDailyUseSample(
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700872 const scoped_ptr<PersistentInteger>& use) {
873 SendSample(use->Name(),
874 use->GetAndClear(),
875 1, // value of first bucket
876 kSecondsPerDay, // value of last bucket
877 50); // number of buckets
878}
879
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700880void MetricsDaemon::SendAndResetCrashIntervalSample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800881 const scoped_ptr<PersistentInteger>& interval) {
882 SendSample(interval->Name(),
883 interval->GetAndClear(),
884 1, // value of first bucket
885 4 * kSecondsPerWeek, // value of last bucket
886 50); // number of buckets
887}
888
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700889void MetricsDaemon::SendAndResetCrashFrequencySample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800890 const scoped_ptr<PersistentInteger>& frequency) {
891 SendSample(frequency->Name(),
892 frequency->GetAndClear(),
893 1, // value of first bucket
894 100, // value of last bucket
895 50); // number of buckets
896}
897
898void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700899 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700900 // TODO(semenzato): add a proper linear histogram to the Chrome external
901 // metrics API.
902 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
903 metrics_lib_->SendEnumToUMA(name, sample, max);
904}
Daniel Eratc83975a2014-04-04 08:53:44 -0700905
906void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
907 Time now_wall_time) {
908 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700909 daily_active_use_->Add(elapsed_seconds);
910 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -0700911 user_crash_interval_->Add(elapsed_seconds);
912 kernel_crash_interval_->Add(elapsed_seconds);
913 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
914 last_update_stats_time_ = now_ticks;
915
916 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
917 const int day = since_epoch.InDays();
918 const int week = day / 7;
919
920 if (daily_cycle_->Get() != day) {
921 daily_cycle_->Set(day);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700922 SendAndResetDailyUseSample(daily_active_use_);
923 SendAndResetCrashFrequencySample(any_crashes_daily_count_);
924 SendAndResetCrashFrequencySample(user_crashes_daily_count_);
925 SendAndResetCrashFrequencySample(kernel_crashes_daily_count_);
926 SendAndResetCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700927 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -0700928 }
929
930 if (weekly_cycle_->Get() != week) {
931 weekly_cycle_->Set(week);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700932 SendAndResetCrashFrequencySample(any_crashes_weekly_count_);
933 SendAndResetCrashFrequencySample(user_crashes_weekly_count_);
934 SendAndResetCrashFrequencySample(kernel_crashes_weekly_count_);
935 SendAndResetCrashFrequencySample(unclean_shutdowns_weekly_count_);
Daniel Eratc83975a2014-04-04 08:53:44 -0700936 }
937}
938
Steve Funge86591e2014-12-01 13:38:21 -0800939void MetricsDaemon::HandleUpdateStatsTimeout() {
940 UpdateStats(TimeTicks::Now(), Time::Now());
941 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
942 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
943 base::Unretained(this)),
944 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -0700945}