blob: b606fd0ca80c18426b8b469abf20d5594f712e89 [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 kMeminfoFileName[] = "/proc/meminfo";
Bertrand SIMONNET7a964052015-09-29 11:07:24 -070075const char kVmStatFileName[] = "/proc/vmstat";
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -070076
Luigi Semenzatofb3a8212013-05-07 16:55:00 -070077// Thermal CPU throttling.
78
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070079const char kMetricScaledCpuFrequencyName[] =
Luigi Semenzatofb3a8212013-05-07 16:55:00 -070080 "Platform.CpuFrequencyThermalScaling";
81
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070082} // namespace
83
Luigi Semenzato96360192014-06-04 10:53:35 -070084// Zram sysfs entries.
85
86const char MetricsDaemon::kComprDataSizeName[] = "compr_data_size";
87const char MetricsDaemon::kOrigDataSizeName[] = "orig_data_size";
88const char MetricsDaemon::kZeroPagesName[] = "zero_pages";
89
Luigi Semenzato8accd332011-05-17 16:37:18 -070090// Memory use stats collection intervals. We collect some memory use interval
91// at these intervals after boot, and we stop collecting after the last one,
92// with the assumption that in most cases the memory use won't change much
93// after that.
94static const int kMemuseIntervals[] = {
95 1 * kSecondsPerMinute, // 1 minute mark
96 4 * kSecondsPerMinute, // 5 minute mark
97 25 * kSecondsPerMinute, // 0.5 hour mark
98 120 * kSecondsPerMinute, // 2.5 hour mark
99 600 * kSecondsPerMinute, // 12.5 hour mark
100};
101
Darin Petkovf1e85e42010-06-10 15:59:53 -0700102MetricsDaemon::MetricsDaemon()
Steve Funge86591e2014-12-01 13:38:21 -0800103 : memuse_final_time_(0),
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800104 memuse_interval_index_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700105
Ken Mixter4c5daa42010-08-26 18:35:06 -0700106MetricsDaemon::~MetricsDaemon() {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700107}
108
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700109// static
Luigi Semenzato8accd332011-05-17 16:37:18 -0700110double MetricsDaemon::GetActiveTime() {
111 struct timespec ts;
112 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
113 if (r < 0) {
114 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
115 return 0;
116 } else {
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700117 return ts.tv_sec + static_cast<double>(ts.tv_nsec) / (1000 * 1000 * 1000);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700118 }
119}
120
Steve Funge86591e2014-12-01 13:38:21 -0800121int MetricsDaemon::Run() {
Ken Mixterccd84c02010-08-16 19:57:13 -0700122 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
123 ProcessKernelCrash();
124 }
125
126 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
127 ProcessUncleanShutdown();
128 }
129
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800130 // On OS version change, clear version stats (which are reported daily).
Ben Chanf05ab402014-08-07 00:54:59 -0700131 int32_t version = GetOsVersionHash();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800132 if (version_cycle_->Get() != version) {
133 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800134 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700135 version_cumulative_active_use_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700136 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800137 }
138
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700139 return brillo::DBusDaemon::Run();
Darin Petkov65b01462010-04-14 13:32:20 -0700140}
141
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700142void MetricsDaemon::RunUploaderTest() {
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700143 upload_service_.reset(new UploadService(
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700144 new SystemProfileCache(true, metrics_directory_),
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700145 metrics_lib_,
146 server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700147 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700148 upload_service_->UploadEvent();
149}
150
Ben Chanf05ab402014-08-07 00:54:59 -0700151uint32_t MetricsDaemon::GetOsVersionHash() {
Bertrand SIMONNETeb697ab2015-10-14 13:26:42 -0700152 brillo::OsReleaseReader reader;
153 reader.Load();
154 string version;
155 if (!reader.GetString(metrics::kProductVersion, &version)) {
156 LOG(ERROR) << "failed to read the product version.";
157 version = metrics::kDefaultVersion;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800158 }
Bertrand SIMONNETeb697ab2015-10-14 13:26:42 -0700159
160 uint32_t version_hash = base::Hash(version);
161 if (testing_) {
162 version_hash = 42; // return any plausible value for the hash
163 }
164 return version_hash;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800165}
166
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700167void MetricsDaemon::Init(bool testing,
168 bool uploader_active,
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700169 bool dbus_enabled,
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700170 MetricsLibraryInterface* metrics_lib,
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700171 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700172 const string& scaling_max_freq_path,
Steve Fung67906c62014-10-06 15:15:30 -0700173 const string& cpuinfo_max_freq_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700174 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700175 const string& server,
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700176 const base::FilePath& metrics_directory) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700177 CHECK(metrics_lib);
Darin Petkov65b01462010-04-14 13:32:20 -0700178 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800179 uploader_active_ = uploader_active;
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700180 dbus_enabled_ = dbus_enabled;
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700181 metrics_directory_ = metrics_directory;
Darin Petkovfc91b422010-05-12 13:05:45 -0700182 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700183
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700184 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700185 server_ = server;
Steve Fung67906c62014-10-06 15:15:30 -0700186
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700187 daily_active_use_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700188 new PersistentInteger("Platform.UseTime.PerDay"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700189 version_cumulative_active_use_.reset(
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700190 new PersistentInteger("Platform.CumulativeUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700191 version_cumulative_cpu_use_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700192 new PersistentInteger("Platform.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700193
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800194 kernel_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700195 new PersistentInteger("Platform.KernelCrashInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800196 unclean_shutdown_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700197 new PersistentInteger("Platform.UncleanShutdownInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800198 user_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700199 new PersistentInteger("Platform.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700200
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800201 any_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700202 new PersistentInteger("Platform.AnyCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800203 any_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700204 new PersistentInteger("Platform.AnyCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800205 user_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700206 new PersistentInteger("Platform.UserCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800207 user_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700208 new PersistentInteger("Platform.UserCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800209 kernel_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700210 new PersistentInteger("Platform.KernelCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800211 kernel_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700212 new PersistentInteger("Platform.KernelCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800213 kernel_crashes_version_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700214 new PersistentInteger("Platform.KernelCrashesSinceUpdate"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800215 unclean_shutdowns_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700216 new PersistentInteger("Platform.UncleanShutdown.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800217 unclean_shutdowns_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700218 new PersistentInteger("Platform.UncleanShutdowns.PerWeek"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700219
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800220 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
221 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
222 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800223
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700224 scaling_max_freq_path_ = scaling_max_freq_path;
225 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700226 disk_usage_collector_.reset(new DiskUsageCollector(metrics_lib_));
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700227 averaged_stats_collector_.reset(
228 new AveragedStatisticsCollector(metrics_lib_, diskstats_path,
229 kVmStatFileName));
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800230 cpu_usage_collector_.reset(new CpuUsageCollector(metrics_lib_));
Steve Funge86591e2014-12-01 13:38:21 -0800231}
232
233int MetricsDaemon::OnInit() {
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700234 int return_code = dbus_enabled_ ? brillo::DBusDaemon::OnInit() :
235 brillo::Daemon::OnInit();
Steve Funge86591e2014-12-01 13:38:21 -0800236 if (return_code != EX_OK)
237 return return_code;
238
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700239 StatsReporterInit();
240
241 // Start collecting meminfo stats.
242 ScheduleMeminfoCallback(kMetricMeminfoInterval);
243 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
244 ScheduleMemuseCallback(kMemuseIntervals[0]);
245
Steve Funge86591e2014-12-01 13:38:21 -0800246 if (testing_)
247 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700248
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700249 if (dbus_enabled_) {
250 bus_->AssertOnDBusThread();
251 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700252
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700253 if (bus_->is_connected()) {
254 const std::string match_rule =
255 base::StringPrintf(kCrashReporterMatchRule,
256 kCrashReporterInterface,
257 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700258
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700259 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700260
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700261 DBusError error;
262 dbus_error_init(&error);
263 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700264
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700265 if (dbus_error_is_set(&error)) {
266 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
267 << error.name << ": " << error.message;
268 return EX_SOFTWARE;
269 }
270 } else {
271 LOG(ERROR) << "DBus isn't connected.";
272 return EX_UNAVAILABLE;
Steve Funge86591e2014-12-01 13:38:21 -0800273 }
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700274
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700275 device_ = weaved::Device::CreateInstance(
276 bus_,
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700277 base::Bind(&MetricsDaemon::UpdateWeaveState, base::Unretained(this)));
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700278 device_->AddCommandHandler(
279 "_metrics._enableAnalyticsReporting",
280 base::Bind(&MetricsDaemon::OnEnableMetrics, base::Unretained(this)));
281 device_->AddCommandHandler(
282 "_metrics._disableAnalyticsReporting",
283 base::Bind(&MetricsDaemon::OnDisableMetrics, base::Unretained(this)));
Darin Petkov703ec972010-04-27 11:02:18 -0700284 }
285
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800286 latest_cpu_use_microseconds_ = cpu_usage_collector_->GetCumulativeCpuUse();
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700287 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
288 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
289 base::Unretained(this)),
290 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
291
Steve Funge86591e2014-12-01 13:38:21 -0800292 if (uploader_active_) {
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700293 upload_service_.reset(
294 new UploadService(new SystemProfileCache(), metrics_lib_, server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700295 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700296 }
Steve Funge86591e2014-12-01 13:38:21 -0800297
298 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700299}
300
Steve Funge86591e2014-12-01 13:38:21 -0800301void MetricsDaemon::OnShutdown(int* return_code) {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700302 if (!testing_ && dbus_enabled_ && bus_->is_connected()) {
Steve Funge86591e2014-12-01 13:38:21 -0800303 const std::string match_rule =
304 base::StringPrintf(kCrashReporterMatchRule,
305 kCrashReporterInterface,
306 kCrashReporterUserCrashSignal);
307
308 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
309
310 DBusError error;
311 dbus_error_init(&error);
312 bus_->RemoveMatch(match_rule, &error);
313
314 if (dbus_error_is_set(&error)) {
315 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
316 << error.name << ": " << error.message;
317 }
318 }
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700319 brillo::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700320}
321
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700322void MetricsDaemon::OnEnableMetrics(const std::weak_ptr<weaved::Command>& cmd) {
323 auto command = cmd.lock();
324 if (!command)
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700325 return;
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700326
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700327 if (base::WriteFile(metrics_directory_.Append(metrics::kConsentFileName),
328 "", 0) != 0) {
329 PLOG(ERROR) << "Could not create the consent file.";
Alex Vakulenko35f89632015-10-09 08:18:35 -0700330 command->Abort("metrics_error", "Could not create the consent file",
331 nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700332 return;
333 }
334
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700335 UpdateWeaveState();
Alex Vakulenko35f89632015-10-09 08:18:35 -0700336 command->Complete({}, nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700337}
338
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700339void MetricsDaemon::OnDisableMetrics(
340 const std::weak_ptr<weaved::Command>& cmd) {
341 auto command = cmd.lock();
342 if (!command)
343 return;
344
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700345 if (!base::DeleteFile(metrics_directory_.Append(metrics::kConsentFileName),
346 false)) {
Alex Vakulenko35f89632015-10-09 08:18:35 -0700347 PLOG(ERROR) << "Could not delete the consent file.";
348 command->Abort("metrics_error", "Could not delete the consent file",
349 nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700350 return;
351 }
352
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700353 UpdateWeaveState();
Alex Vakulenko35f89632015-10-09 08:18:35 -0700354 command->Complete({}, nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700355}
356
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700357void MetricsDaemon::UpdateWeaveState() {
358 if (!device_)
359 return;
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700360
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700361 brillo::VariantDictionary state_change{
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700362 { "_metrics._AnalyticsReportingState",
363 metrics_lib_->AreMetricsEnabled() ? "enabled" : "disabled" }
364 };
365
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700366 if (!device_->SetStateProperties(state_change, nullptr)) {
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700367 LOG(ERROR) << "failed to update weave's state";
368 }
369}
370
Darin Petkov703ec972010-04-27 11:02:18 -0700371// static
372DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
373 DBusMessage* message,
374 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700375 int message_type = dbus_message_get_type(message);
376 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700377 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700378 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
379 }
380
381 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700382 const std::string interface(dbus_message_get_interface(message));
383 const std::string member(dbus_message_get_member(message));
384 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700385
386 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
387
388 DBusMessageIter iter;
389 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700390 if (interface == kCrashReporterInterface) {
391 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700392 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700393 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700394 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700395 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
396 }
397
398 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700399}
400
Darin Petkov1bb904e2010-06-16 15:58:06 -0700401void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700402 // Counts the active time up to now.
403 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700404
405 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700406 SendAndResetCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700407
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800408 any_crashes_daily_count_->Add(1);
409 any_crashes_weekly_count_->Add(1);
410 user_crashes_daily_count_->Add(1);
411 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700412}
413
Darin Petkov38d5cb02010-06-24 12:10:26 -0700414void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700415 // Counts the active time up to now.
416 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700417
418 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700419 SendAndResetCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700420
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800421 any_crashes_daily_count_->Add(1);
422 any_crashes_weekly_count_->Add(1);
423 kernel_crashes_daily_count_->Add(1);
424 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800425
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800426 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700427}
428
Ken Mixterccd84c02010-08-16 19:57:13 -0700429void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700430 // Counts the active time up to now.
431 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700432
433 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700434 SendAndResetCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700435
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800436 unclean_shutdowns_daily_count_->Add(1);
437 unclean_shutdowns_weekly_count_->Add(1);
438 any_crashes_daily_count_->Add(1);
439 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700440}
441
Luigi Semenzato8accd332011-05-17 16:37:18 -0700442bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700443 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800444 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700445 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700446
447 // Deletes the crash-detected file so that the daemon doesn't report
448 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800449 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700450 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700451}
452
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700453void MetricsDaemon::StatsReporterInit() {
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700454 disk_usage_collector_->Schedule();
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700455
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800456 cpu_usage_collector_->Init();
457 cpu_usage_collector_->Schedule();
458
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700459 // Don't start a collection cycle during the first run to avoid delaying the
460 // boot.
461 averaged_stats_collector_->ScheduleWait();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800462}
463
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800464
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700465bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700466 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700467 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800468 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700469 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
470 return false;
471 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800472 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700473 LOG(WARNING) << "no newline in " << value_string;
474 // Continue even though the lack of newline is suspicious.
475 }
476 if (!base::StringToInt(value_string, value)) {
477 LOG(WARNING) << "cannot convert " << value_string << " to int";
478 return false;
479 }
480 return true;
481}
482
483void MetricsDaemon::SendCpuThrottleMetrics() {
484 // |max_freq| is 0 only the first time through.
485 static int max_freq = 0;
486 if (max_freq == -1)
487 // Give up, as sysfs did not report max_freq correctly.
488 return;
489 if (max_freq == 0 || testing_) {
490 // One-time initialization of max_freq. (Every time when testing.)
491 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
492 max_freq = -1;
493 return;
494 }
495 if (max_freq == 0) {
496 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
497 max_freq = -1;
498 return;
499 }
500 if (max_freq % 10000 == 1000) {
501 // Special case: system has turbo mode, and max non-turbo frequency is
502 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
503 // being multiples of (at least) 10 MHz. Although there is no guarantee
504 // of this, it seems a fairly reasonable assumption. Otherwise we should
505 // read scaling_available_frequencies, sort the frequencies, compare the
506 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
507 // hack too, no telling when it will change).
508 max_freq -= 1000;
509 }
510 }
511 int scaled_freq = 0;
512 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
513 return;
514 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
515 // scaled_freq is not the actual turbo frequency. We indicate this situation
516 // with a 101% value.
517 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800518 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700519}
520
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700521void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
522 if (testing_) {
523 return;
524 }
Steve Funge86591e2014-12-01 13:38:21 -0800525 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
526 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
527 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800528 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800529 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700530}
531
Steve Funge86591e2014-12-01 13:38:21 -0800532void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700533 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700534 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800535 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700536 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800537 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700538 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700539 // Make both calls even if the first one fails.
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700540 if (ProcessMeminfo(meminfo_raw)) {
Steve Funge86591e2014-12-01 13:38:21 -0800541 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
542 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800543 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800544 wait);
545 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700546}
547
548// static
549bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700550 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700551 std::string content;
552 if (!base::ReadFileToString(path, &content)) {
553 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
554 return false;
555 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700556 // Remove final newline.
557 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700558 if (!base::StringToUint64(content, value)) {
559 LOG(WARNING) << "invalid integer: " << content;
560 return false;
561 }
562 return true;
563}
564
565bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
566 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700567 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700568 const size_t page_size = 4096;
569
570 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
571 &compr_data_size) ||
572 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
573 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
574 return false;
575 }
576
577 // |orig_data_size| does not include zero-filled pages.
578 orig_data_size += zero_pages * page_size;
579
580 const int compr_data_size_mb = compr_data_size >> 20;
581 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
582 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
583
584 // Report compressed size in megabytes. 100 MB or less has little impact.
585 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
586 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
587 // The compression ratio is multiplied by 100 for better resolution. The
588 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
589 // don't want samples when very little memory is being compressed.
590 if (compr_data_size_mb >= 1) {
591 SendSample("Platform.ZramCompressionRatioPercent",
592 orig_data_size * 100 / compr_data_size, 100, 600, 50);
593 }
594 // The values of interest for zero_pages are between 1MB and 1GB. The units
595 // are number of pages.
596 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
597 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
598
599 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700600}
601
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700602bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700603 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700604 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
605 { "MemFree", "MemFree" },
606 { "Buffers", "Buffers" },
607 { "Cached", "Cached" },
608 // { "SwapCached", "SwapCached" },
609 { "Active", "Active" },
610 { "Inactive", "Inactive" },
611 { "ActiveAnon", "Active(anon)" },
612 { "InactiveAnon", "Inactive(anon)" },
613 { "ActiveFile" , "Active(file)" },
614 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800615 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700616 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800617 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
618 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700619 // { "Dirty", "Dirty" },
620 // { "Writeback", "Writeback" },
621 { "AnonPages", "AnonPages" },
622 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800623 { "Shmem", "Shmem", kMeminfoOp_HistLog },
624 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700625 // { "SReclaimable", "SReclaimable" },
626 // { "SUnreclaim", "SUnreclaim" },
627 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700628 vector<MeminfoRecord> fields(fields_array,
629 fields_array + arraysize(fields_array));
630 if (!FillMeminfo(meminfo_raw, &fields)) {
631 return false;
632 }
633 int total_memory = fields[0].value;
634 if (total_memory == 0) {
635 // this "cannot happen"
636 LOG(WARNING) << "borked meminfo parser";
637 return false;
638 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800639 int swap_total = 0;
640 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700641 // Send all fields retrieved, except total memory.
642 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800643 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
644 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800645 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800646 switch (fields[i].op) {
647 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800648 // report value as percent of total memory
649 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800650 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800651 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800652 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800653 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800654 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800655 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800656 case kMeminfoOp_SwapTotal:
657 swap_total = fields[i].value;
658 case kMeminfoOp_SwapFree:
659 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800660 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700661 }
662 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800663 if (swap_total > 0) {
664 int swap_used = swap_total - swap_free;
665 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800666 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -0700667 SendLinearSample("Platform.MeminfoSwapUsed.Percent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800668 100, 101);
669 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700670 return true;
671}
672
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700673bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
674 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700675 vector<string> lines;
676 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700677
678 // Scan meminfo output and collect field values. Each field name has to
679 // match a meminfo entry (case insensitive) after removing non-alpha
680 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700681 unsigned int ifield = 0;
682 for (unsigned int iline = 0;
683 iline < nlines && ifield < fields->size();
684 iline++) {
685 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700686 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700687 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
688 // Name matches. Parse value and save.
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700689 if (!base::StringToInt(tokens[1], &(*fields)[ifield].value)) {
690 LOG(WARNING) << "Cound not convert " << tokens[1] << " to int";
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700691 return false;
692 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700693 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700694 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700695 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700696 if (ifield < fields->size()) {
697 // End of input reached while scanning.
698 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
699 << " and following";
700 return false;
701 }
702 return true;
703}
704
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800705void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700706 if (testing_) {
707 return;
708 }
Steve Funge86591e2014-12-01 13:38:21 -0800709 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
710 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
711 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700712}
713
714void MetricsDaemon::MemuseCallback() {
715 // Since we only care about active time (i.e. uptime minus sleep time) but
716 // the callbacks are driven by real time (uptime), we check if we should
717 // reschedule this callback due to intervening sleep periods.
718 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800719 // Avoid intervals of less than one second.
720 double remaining_time = ceil(memuse_final_time_ - now);
721 if (remaining_time > 0) {
722 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700723 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800724 // Report stats and advance the measurement interval unless there are
725 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700726 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800727 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
728 double interval = kMemuseIntervals[memuse_interval_index_++];
729 memuse_final_time_ = now + interval;
730 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700731 }
732 }
733}
734
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700735bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700736 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700737 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800738 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700739 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
740 return false;
741 }
742 return ProcessMemuse(meminfo_raw);
743}
744
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700745bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700746 static const MeminfoRecord fields_array[] = {
747 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
748 { "ActiveAnon", "Active(anon)" },
749 { "InactiveAnon", "Inactive(anon)" },
750 };
751 vector<MeminfoRecord> fields(fields_array,
752 fields_array + arraysize(fields_array));
753 if (!FillMeminfo(meminfo_raw, &fields)) {
754 return false;
755 }
756 int total = fields[0].value;
757 int active_anon = fields[1].value;
758 int inactive_anon = fields[2].value;
759 if (total == 0) {
760 // this "cannot happen"
761 LOG(WARNING) << "borked meminfo parser";
762 return false;
763 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800764 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
765 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800766 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -0700767 100, 101);
768 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700769}
770
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800771void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -0700772 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -0700773 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700774}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700775
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700776void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800777 // Report the number of crashes for this OS version, but don't clear the
778 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -0700779 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800780 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700781 crashes_count,
782 1, // value of first bucket
783 500, // value of last bucket
784 100); // number of buckets
785
786
Ben Chanf05ab402014-08-07 00:54:59 -0700787 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700788 SendSample(version_cumulative_cpu_use_->Name(),
789 cpu_use_ms / 1000, // stat is in seconds
790 1, // device may be used very little...
791 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
792 100);
793
794 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
795 // can be zero. Avoid division by zero.
796 if (cpu_use_ms > 0) {
797 // Send the crash frequency since update in number of crashes per CPU year.
798 SendSample("Logging.KernelCrashesPerCpuYear",
799 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
800 1,
801 1000 * 1000, // about one crash every 30s of CPU time
802 100);
803 }
804
Ben Chanf05ab402014-08-07 00:54:59 -0700805 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700806 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700807 SendSample(version_cumulative_active_use_->Name(),
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700808 active_use_seconds,
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700809 1, // device may be used very little...
810 8 * 1000 * 1000, // ... or a lot (about 90 days)
811 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700812 // Same as above, but per year of active time.
813 SendSample("Logging.KernelCrashesPerActiveYear",
814 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
815 1,
816 1000 * 1000, // about one crash every 30s of active time
817 100);
818 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800819}
820
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700821void MetricsDaemon::SendAndResetDailyUseSample(
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700822 const scoped_ptr<PersistentInteger>& use) {
823 SendSample(use->Name(),
824 use->GetAndClear(),
825 1, // value of first bucket
826 kSecondsPerDay, // value of last bucket
827 50); // number of buckets
828}
829
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700830void MetricsDaemon::SendAndResetCrashIntervalSample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800831 const scoped_ptr<PersistentInteger>& interval) {
832 SendSample(interval->Name(),
833 interval->GetAndClear(),
834 1, // value of first bucket
835 4 * kSecondsPerWeek, // value of last bucket
836 50); // number of buckets
837}
838
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700839void MetricsDaemon::SendAndResetCrashFrequencySample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800840 const scoped_ptr<PersistentInteger>& frequency) {
841 SendSample(frequency->Name(),
842 frequency->GetAndClear(),
843 1, // value of first bucket
844 100, // value of last bucket
845 50); // number of buckets
846}
847
848void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700849 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700850 // TODO(semenzato): add a proper linear histogram to the Chrome external
851 // metrics API.
852 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
853 metrics_lib_->SendEnumToUMA(name, sample, max);
854}
Daniel Eratc83975a2014-04-04 08:53:44 -0700855
856void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
857 Time now_wall_time) {
858 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700859 daily_active_use_->Add(elapsed_seconds);
860 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -0700861 user_crash_interval_->Add(elapsed_seconds);
862 kernel_crash_interval_->Add(elapsed_seconds);
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800863 TimeDelta cpu_use = cpu_usage_collector_->GetCumulativeCpuUse();
864 version_cumulative_cpu_use_->Add(
865 (cpu_use - latest_cpu_use_microseconds_).InMilliseconds());
866 latest_cpu_use_microseconds_ = cpu_use;
Daniel Eratc83975a2014-04-04 08:53:44 -0700867 last_update_stats_time_ = now_ticks;
868
869 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
870 const int day = since_epoch.InDays();
871 const int week = day / 7;
872
873 if (daily_cycle_->Get() != day) {
874 daily_cycle_->Set(day);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700875 SendAndResetDailyUseSample(daily_active_use_);
876 SendAndResetCrashFrequencySample(any_crashes_daily_count_);
877 SendAndResetCrashFrequencySample(user_crashes_daily_count_);
878 SendAndResetCrashFrequencySample(kernel_crashes_daily_count_);
879 SendAndResetCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700880 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -0700881 }
882
883 if (weekly_cycle_->Get() != week) {
884 weekly_cycle_->Set(week);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700885 SendAndResetCrashFrequencySample(any_crashes_weekly_count_);
886 SendAndResetCrashFrequencySample(user_crashes_weekly_count_);
887 SendAndResetCrashFrequencySample(kernel_crashes_weekly_count_);
888 SendAndResetCrashFrequencySample(unclean_shutdowns_weekly_count_);
Daniel Eratc83975a2014-04-04 08:53:44 -0700889 }
890}
891
Steve Funge86591e2014-12-01 13:38:21 -0800892void MetricsDaemon::HandleUpdateStatsTimeout() {
893 UpdateStats(TimeTicks::Now(), Time::Now());
894 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
895 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
896 base::Unretained(this)),
897 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -0700898}