blob: e711660c6dd467ad58c7a936f6e40a5c3b74b767 [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
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070077} // namespace
78
Luigi Semenzato96360192014-06-04 10:53:35 -070079// Zram sysfs entries.
80
81const char MetricsDaemon::kComprDataSizeName[] = "compr_data_size";
82const char MetricsDaemon::kOrigDataSizeName[] = "orig_data_size";
83const char MetricsDaemon::kZeroPagesName[] = "zero_pages";
84
Luigi Semenzato8accd332011-05-17 16:37:18 -070085// Memory use stats collection intervals. We collect some memory use interval
86// at these intervals after boot, and we stop collecting after the last one,
87// with the assumption that in most cases the memory use won't change much
88// after that.
89static const int kMemuseIntervals[] = {
90 1 * kSecondsPerMinute, // 1 minute mark
91 4 * kSecondsPerMinute, // 5 minute mark
92 25 * kSecondsPerMinute, // 0.5 hour mark
93 120 * kSecondsPerMinute, // 2.5 hour mark
94 600 * kSecondsPerMinute, // 12.5 hour mark
95};
96
Darin Petkovf1e85e42010-06-10 15:59:53 -070097MetricsDaemon::MetricsDaemon()
Steve Funge86591e2014-12-01 13:38:21 -080098 : memuse_final_time_(0),
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -080099 memuse_interval_index_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700100
Ken Mixter4c5daa42010-08-26 18:35:06 -0700101MetricsDaemon::~MetricsDaemon() {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700102}
103
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700104// static
Luigi Semenzato8accd332011-05-17 16:37:18 -0700105double MetricsDaemon::GetActiveTime() {
106 struct timespec ts;
107 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
108 if (r < 0) {
109 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
110 return 0;
111 } else {
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700112 return ts.tv_sec + static_cast<double>(ts.tv_nsec) / (1000 * 1000 * 1000);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700113 }
114}
115
Steve Funge86591e2014-12-01 13:38:21 -0800116int MetricsDaemon::Run() {
Ken Mixterccd84c02010-08-16 19:57:13 -0700117 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
118 ProcessKernelCrash();
119 }
120
121 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
122 ProcessUncleanShutdown();
123 }
124
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800125 // On OS version change, clear version stats (which are reported daily).
Ben Chanf05ab402014-08-07 00:54:59 -0700126 int32_t version = GetOsVersionHash();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800127 if (version_cycle_->Get() != version) {
128 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800129 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700130 version_cumulative_active_use_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700131 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800132 }
133
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700134 return brillo::DBusDaemon::Run();
Darin Petkov65b01462010-04-14 13:32:20 -0700135}
136
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700137void MetricsDaemon::RunUploaderTest() {
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700138 upload_service_.reset(new UploadService(
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700139 new SystemProfileCache(true, metrics_directory_),
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700140 metrics_lib_,
141 server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700142 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700143 upload_service_->UploadEvent();
144}
145
Ben Chanf05ab402014-08-07 00:54:59 -0700146uint32_t MetricsDaemon::GetOsVersionHash() {
Bertrand SIMONNETeb697ab2015-10-14 13:26:42 -0700147 brillo::OsReleaseReader reader;
148 reader.Load();
149 string version;
150 if (!reader.GetString(metrics::kProductVersion, &version)) {
151 LOG(ERROR) << "failed to read the product version.";
152 version = metrics::kDefaultVersion;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800153 }
Bertrand SIMONNETeb697ab2015-10-14 13:26:42 -0700154
155 uint32_t version_hash = base::Hash(version);
156 if (testing_) {
157 version_hash = 42; // return any plausible value for the hash
158 }
159 return version_hash;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800160}
161
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700162void MetricsDaemon::Init(bool testing,
163 bool uploader_active,
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700164 bool dbus_enabled,
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700165 MetricsLibraryInterface* metrics_lib,
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700166 const string& diskstats_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700167 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700168 const string& server,
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700169 const base::FilePath& metrics_directory) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700170 CHECK(metrics_lib);
Darin Petkov65b01462010-04-14 13:32:20 -0700171 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800172 uploader_active_ = uploader_active;
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700173 dbus_enabled_ = dbus_enabled;
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700174 metrics_directory_ = metrics_directory;
Darin Petkovfc91b422010-05-12 13:05:45 -0700175 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700176
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700177 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700178 server_ = server;
Steve Fung67906c62014-10-06 15:15:30 -0700179
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700180 daily_active_use_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700181 new PersistentInteger("Platform.UseTime.PerDay"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700182 version_cumulative_active_use_.reset(
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700183 new PersistentInteger("Platform.CumulativeUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700184 version_cumulative_cpu_use_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700185 new PersistentInteger("Platform.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700186
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800187 kernel_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700188 new PersistentInteger("Platform.KernelCrashInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800189 unclean_shutdown_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700190 new PersistentInteger("Platform.UncleanShutdownInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800191 user_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700192 new PersistentInteger("Platform.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700193
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800194 any_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700195 new PersistentInteger("Platform.AnyCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800196 any_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700197 new PersistentInteger("Platform.AnyCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800198 user_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700199 new PersistentInteger("Platform.UserCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800200 user_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700201 new PersistentInteger("Platform.UserCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800202 kernel_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700203 new PersistentInteger("Platform.KernelCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800204 kernel_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700205 new PersistentInteger("Platform.KernelCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800206 kernel_crashes_version_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700207 new PersistentInteger("Platform.KernelCrashesSinceUpdate"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800208 unclean_shutdowns_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700209 new PersistentInteger("Platform.UncleanShutdown.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800210 unclean_shutdowns_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700211 new PersistentInteger("Platform.UncleanShutdowns.PerWeek"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700212
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800213 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
214 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
215 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800216
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700217 disk_usage_collector_.reset(new DiskUsageCollector(metrics_lib_));
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700218 averaged_stats_collector_.reset(
219 new AveragedStatisticsCollector(metrics_lib_, diskstats_path,
220 kVmStatFileName));
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800221 cpu_usage_collector_.reset(new CpuUsageCollector(metrics_lib_));
Steve Funge86591e2014-12-01 13:38:21 -0800222}
223
224int MetricsDaemon::OnInit() {
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700225 int return_code = dbus_enabled_ ? brillo::DBusDaemon::OnInit() :
226 brillo::Daemon::OnInit();
Steve Funge86591e2014-12-01 13:38:21 -0800227 if (return_code != EX_OK)
228 return return_code;
229
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700230 StatsReporterInit();
231
232 // Start collecting meminfo stats.
233 ScheduleMeminfoCallback(kMetricMeminfoInterval);
234 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
235 ScheduleMemuseCallback(kMemuseIntervals[0]);
236
Steve Funge86591e2014-12-01 13:38:21 -0800237 if (testing_)
238 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700239
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700240 if (dbus_enabled_) {
241 bus_->AssertOnDBusThread();
242 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700243
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700244 if (bus_->is_connected()) {
245 const std::string match_rule =
246 base::StringPrintf(kCrashReporterMatchRule,
247 kCrashReporterInterface,
248 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700249
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700250 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700251
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700252 DBusError error;
253 dbus_error_init(&error);
254 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700255
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700256 if (dbus_error_is_set(&error)) {
257 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
258 << error.name << ": " << error.message;
259 return EX_SOFTWARE;
260 }
261 } else {
262 LOG(ERROR) << "DBus isn't connected.";
263 return EX_UNAVAILABLE;
Steve Funge86591e2014-12-01 13:38:21 -0800264 }
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700265
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700266 device_ = weaved::Device::CreateInstance(
267 bus_,
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700268 base::Bind(&MetricsDaemon::UpdateWeaveState, base::Unretained(this)));
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700269 device_->AddCommandHandler(
270 "_metrics._enableAnalyticsReporting",
271 base::Bind(&MetricsDaemon::OnEnableMetrics, base::Unretained(this)));
272 device_->AddCommandHandler(
273 "_metrics._disableAnalyticsReporting",
274 base::Bind(&MetricsDaemon::OnDisableMetrics, base::Unretained(this)));
Darin Petkov703ec972010-04-27 11:02:18 -0700275 }
276
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800277 latest_cpu_use_microseconds_ = cpu_usage_collector_->GetCumulativeCpuUse();
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700278 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
279 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
280 base::Unretained(this)),
281 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
282
Steve Funge86591e2014-12-01 13:38:21 -0800283 if (uploader_active_) {
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700284 upload_service_.reset(
285 new UploadService(new SystemProfileCache(), metrics_lib_, server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700286 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700287 }
Steve Funge86591e2014-12-01 13:38:21 -0800288
289 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700290}
291
Steve Funge86591e2014-12-01 13:38:21 -0800292void MetricsDaemon::OnShutdown(int* return_code) {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700293 if (!testing_ && dbus_enabled_ && bus_->is_connected()) {
Steve Funge86591e2014-12-01 13:38:21 -0800294 const std::string match_rule =
295 base::StringPrintf(kCrashReporterMatchRule,
296 kCrashReporterInterface,
297 kCrashReporterUserCrashSignal);
298
299 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
300
301 DBusError error;
302 dbus_error_init(&error);
303 bus_->RemoveMatch(match_rule, &error);
304
305 if (dbus_error_is_set(&error)) {
306 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
307 << error.name << ": " << error.message;
308 }
309 }
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700310 brillo::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700311}
312
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700313void MetricsDaemon::OnEnableMetrics(const std::weak_ptr<weaved::Command>& cmd) {
314 auto command = cmd.lock();
315 if (!command)
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700316 return;
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700317
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700318 if (base::WriteFile(metrics_directory_.Append(metrics::kConsentFileName),
319 "", 0) != 0) {
320 PLOG(ERROR) << "Could not create the consent file.";
Alex Vakulenko35f89632015-10-09 08:18:35 -0700321 command->Abort("metrics_error", "Could not create the consent file",
322 nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700323 return;
324 }
325
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700326 UpdateWeaveState();
Alex Vakulenko35f89632015-10-09 08:18:35 -0700327 command->Complete({}, nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700328}
329
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700330void MetricsDaemon::OnDisableMetrics(
331 const std::weak_ptr<weaved::Command>& cmd) {
332 auto command = cmd.lock();
333 if (!command)
334 return;
335
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700336 if (!base::DeleteFile(metrics_directory_.Append(metrics::kConsentFileName),
337 false)) {
Alex Vakulenko35f89632015-10-09 08:18:35 -0700338 PLOG(ERROR) << "Could not delete the consent file.";
339 command->Abort("metrics_error", "Could not delete the consent file",
340 nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700341 return;
342 }
343
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700344 UpdateWeaveState();
Alex Vakulenko35f89632015-10-09 08:18:35 -0700345 command->Complete({}, nullptr);
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700346}
347
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700348void MetricsDaemon::UpdateWeaveState() {
349 if (!device_)
350 return;
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700351
Alex Vakulenko74dc6242015-10-13 09:23:34 -0700352 brillo::VariantDictionary state_change{
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700353 { "_metrics._AnalyticsReportingState",
354 metrics_lib_->AreMetricsEnabled() ? "enabled" : "disabled" }
355 };
356
Alex Vakulenko82b02de2015-10-09 20:07:47 -0700357 if (!device_->SetStateProperties(state_change, nullptr)) {
Bertrand SIMONNET59890e22015-10-02 16:45:18 -0700358 LOG(ERROR) << "failed to update weave's state";
359 }
360}
361
Darin Petkov703ec972010-04-27 11:02:18 -0700362// static
363DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
364 DBusMessage* message,
365 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700366 int message_type = dbus_message_get_type(message);
367 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700368 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700369 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
370 }
371
372 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700373 const std::string interface(dbus_message_get_interface(message));
374 const std::string member(dbus_message_get_member(message));
375 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700376
377 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
378
379 DBusMessageIter iter;
380 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700381 if (interface == kCrashReporterInterface) {
382 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700383 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700384 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700385 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700386 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
387 }
388
389 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700390}
391
Darin Petkov1bb904e2010-06-16 15:58:06 -0700392void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700393 // Counts the active time up to now.
394 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700395
396 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700397 SendAndResetCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700398
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800399 any_crashes_daily_count_->Add(1);
400 any_crashes_weekly_count_->Add(1);
401 user_crashes_daily_count_->Add(1);
402 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700403}
404
Darin Petkov38d5cb02010-06-24 12:10:26 -0700405void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700406 // Counts the active time up to now.
407 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700408
409 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700410 SendAndResetCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700411
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800412 any_crashes_daily_count_->Add(1);
413 any_crashes_weekly_count_->Add(1);
414 kernel_crashes_daily_count_->Add(1);
415 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800416
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800417 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700418}
419
Ken Mixterccd84c02010-08-16 19:57:13 -0700420void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700421 // Counts the active time up to now.
422 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700423
424 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700425 SendAndResetCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700426
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800427 unclean_shutdowns_daily_count_->Add(1);
428 unclean_shutdowns_weekly_count_->Add(1);
429 any_crashes_daily_count_->Add(1);
430 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700431}
432
Luigi Semenzato8accd332011-05-17 16:37:18 -0700433bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700434 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800435 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700436 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700437
438 // Deletes the crash-detected file so that the daemon doesn't report
439 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800440 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700441 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700442}
443
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700444void MetricsDaemon::StatsReporterInit() {
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700445 disk_usage_collector_->Schedule();
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700446
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800447 cpu_usage_collector_->Init();
448 cpu_usage_collector_->Schedule();
449
Bertrand SIMONNET7a964052015-09-29 11:07:24 -0700450 // Don't start a collection cycle during the first run to avoid delaying the
451 // boot.
452 averaged_stats_collector_->ScheduleWait();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800453}
454
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700455void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
456 if (testing_) {
457 return;
458 }
Steve Funge86591e2014-12-01 13:38:21 -0800459 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
460 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
461 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800462 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800463 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700464}
465
Steve Funge86591e2014-12-01 13:38:21 -0800466void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700467 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700468 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800469 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700470 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800471 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700472 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700473 // Make both calls even if the first one fails.
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700474 if (ProcessMeminfo(meminfo_raw)) {
Steve Funge86591e2014-12-01 13:38:21 -0800475 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
476 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800477 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800478 wait);
479 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700480}
481
482// static
483bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700484 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700485 std::string content;
486 if (!base::ReadFileToString(path, &content)) {
487 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
488 return false;
489 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700490 // Remove final newline.
491 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700492 if (!base::StringToUint64(content, value)) {
493 LOG(WARNING) << "invalid integer: " << content;
494 return false;
495 }
496 return true;
497}
498
499bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
500 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700501 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700502 const size_t page_size = 4096;
503
504 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
505 &compr_data_size) ||
506 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
507 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
508 return false;
509 }
510
511 // |orig_data_size| does not include zero-filled pages.
512 orig_data_size += zero_pages * page_size;
513
514 const int compr_data_size_mb = compr_data_size >> 20;
515 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
516 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
517
518 // Report compressed size in megabytes. 100 MB or less has little impact.
519 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
520 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
521 // The compression ratio is multiplied by 100 for better resolution. The
522 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
523 // don't want samples when very little memory is being compressed.
524 if (compr_data_size_mb >= 1) {
525 SendSample("Platform.ZramCompressionRatioPercent",
526 orig_data_size * 100 / compr_data_size, 100, 600, 50);
527 }
528 // The values of interest for zero_pages are between 1MB and 1GB. The units
529 // are number of pages.
530 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
531 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
532
533 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700534}
535
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700536bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700537 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700538 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
539 { "MemFree", "MemFree" },
540 { "Buffers", "Buffers" },
541 { "Cached", "Cached" },
542 // { "SwapCached", "SwapCached" },
543 { "Active", "Active" },
544 { "Inactive", "Inactive" },
545 { "ActiveAnon", "Active(anon)" },
546 { "InactiveAnon", "Inactive(anon)" },
547 { "ActiveFile" , "Active(file)" },
548 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800549 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700550 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800551 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
552 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700553 // { "Dirty", "Dirty" },
554 // { "Writeback", "Writeback" },
555 { "AnonPages", "AnonPages" },
556 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800557 { "Shmem", "Shmem", kMeminfoOp_HistLog },
558 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700559 // { "SReclaimable", "SReclaimable" },
560 // { "SUnreclaim", "SUnreclaim" },
561 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700562 vector<MeminfoRecord> fields(fields_array,
563 fields_array + arraysize(fields_array));
564 if (!FillMeminfo(meminfo_raw, &fields)) {
565 return false;
566 }
567 int total_memory = fields[0].value;
568 if (total_memory == 0) {
569 // this "cannot happen"
570 LOG(WARNING) << "borked meminfo parser";
571 return false;
572 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800573 int swap_total = 0;
574 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700575 // Send all fields retrieved, except total memory.
576 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800577 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
578 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800579 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800580 switch (fields[i].op) {
581 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800582 // report value as percent of total memory
583 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800584 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800585 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800586 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800587 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800588 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800589 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800590 case kMeminfoOp_SwapTotal:
591 swap_total = fields[i].value;
592 case kMeminfoOp_SwapFree:
593 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800594 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700595 }
596 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800597 if (swap_total > 0) {
598 int swap_used = swap_total - swap_free;
599 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800600 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -0700601 SendLinearSample("Platform.MeminfoSwapUsed.Percent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800602 100, 101);
603 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700604 return true;
605}
606
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700607bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
608 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700609 vector<string> lines;
610 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700611
612 // Scan meminfo output and collect field values. Each field name has to
613 // match a meminfo entry (case insensitive) after removing non-alpha
614 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700615 unsigned int ifield = 0;
616 for (unsigned int iline = 0;
617 iline < nlines && ifield < fields->size();
618 iline++) {
619 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700620 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700621 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
622 // Name matches. Parse value and save.
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700623 if (!base::StringToInt(tokens[1], &(*fields)[ifield].value)) {
624 LOG(WARNING) << "Cound not convert " << tokens[1] << " to int";
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700625 return false;
626 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700627 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700628 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700629 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700630 if (ifield < fields->size()) {
631 // End of input reached while scanning.
632 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
633 << " and following";
634 return false;
635 }
636 return true;
637}
638
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800639void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700640 if (testing_) {
641 return;
642 }
Steve Funge86591e2014-12-01 13:38:21 -0800643 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
644 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
645 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700646}
647
648void MetricsDaemon::MemuseCallback() {
649 // Since we only care about active time (i.e. uptime minus sleep time) but
650 // the callbacks are driven by real time (uptime), we check if we should
651 // reschedule this callback due to intervening sleep periods.
652 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800653 // Avoid intervals of less than one second.
654 double remaining_time = ceil(memuse_final_time_ - now);
655 if (remaining_time > 0) {
656 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700657 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800658 // Report stats and advance the measurement interval unless there are
659 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700660 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800661 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
662 double interval = kMemuseIntervals[memuse_interval_index_++];
663 memuse_final_time_ = now + interval;
664 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700665 }
666 }
667}
668
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700669bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700670 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700671 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800672 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700673 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
674 return false;
675 }
676 return ProcessMemuse(meminfo_raw);
677}
678
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700679bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700680 static const MeminfoRecord fields_array[] = {
681 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
682 { "ActiveAnon", "Active(anon)" },
683 { "InactiveAnon", "Inactive(anon)" },
684 };
685 vector<MeminfoRecord> fields(fields_array,
686 fields_array + arraysize(fields_array));
687 if (!FillMeminfo(meminfo_raw, &fields)) {
688 return false;
689 }
690 int total = fields[0].value;
691 int active_anon = fields[1].value;
692 int inactive_anon = fields[2].value;
693 if (total == 0) {
694 // this "cannot happen"
695 LOG(WARNING) << "borked meminfo parser";
696 return false;
697 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800698 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
699 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800700 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -0700701 100, 101);
702 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700703}
704
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800705void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -0700706 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -0700707 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700708}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700709
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700710void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800711 // Report the number of crashes for this OS version, but don't clear the
712 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -0700713 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800714 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700715 crashes_count,
716 1, // value of first bucket
717 500, // value of last bucket
718 100); // number of buckets
719
720
Ben Chanf05ab402014-08-07 00:54:59 -0700721 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700722 SendSample(version_cumulative_cpu_use_->Name(),
723 cpu_use_ms / 1000, // stat is in seconds
724 1, // device may be used very little...
725 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
726 100);
727
728 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
729 // can be zero. Avoid division by zero.
730 if (cpu_use_ms > 0) {
731 // Send the crash frequency since update in number of crashes per CPU year.
732 SendSample("Logging.KernelCrashesPerCpuYear",
733 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
734 1,
735 1000 * 1000, // about one crash every 30s of CPU time
736 100);
737 }
738
Ben Chanf05ab402014-08-07 00:54:59 -0700739 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700740 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700741 SendSample(version_cumulative_active_use_->Name(),
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700742 active_use_seconds,
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700743 1, // device may be used very little...
744 8 * 1000 * 1000, // ... or a lot (about 90 days)
745 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700746 // Same as above, but per year of active time.
747 SendSample("Logging.KernelCrashesPerActiveYear",
748 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
749 1,
750 1000 * 1000, // about one crash every 30s of active time
751 100);
752 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800753}
754
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700755void MetricsDaemon::SendAndResetDailyUseSample(
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700756 const scoped_ptr<PersistentInteger>& use) {
757 SendSample(use->Name(),
758 use->GetAndClear(),
759 1, // value of first bucket
760 kSecondsPerDay, // value of last bucket
761 50); // number of buckets
762}
763
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700764void MetricsDaemon::SendAndResetCrashIntervalSample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800765 const scoped_ptr<PersistentInteger>& interval) {
766 SendSample(interval->Name(),
767 interval->GetAndClear(),
768 1, // value of first bucket
769 4 * kSecondsPerWeek, // value of last bucket
770 50); // number of buckets
771}
772
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700773void MetricsDaemon::SendAndResetCrashFrequencySample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800774 const scoped_ptr<PersistentInteger>& frequency) {
775 SendSample(frequency->Name(),
776 frequency->GetAndClear(),
777 1, // value of first bucket
778 100, // value of last bucket
779 50); // number of buckets
780}
781
782void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700783 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700784 // TODO(semenzato): add a proper linear histogram to the Chrome external
785 // metrics API.
786 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
787 metrics_lib_->SendEnumToUMA(name, sample, max);
788}
Daniel Eratc83975a2014-04-04 08:53:44 -0700789
790void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
791 Time now_wall_time) {
792 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700793 daily_active_use_->Add(elapsed_seconds);
794 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -0700795 user_crash_interval_->Add(elapsed_seconds);
796 kernel_crash_interval_->Add(elapsed_seconds);
Bertrand SIMONNET0ada2ca2015-11-02 14:08:44 -0800797 TimeDelta cpu_use = cpu_usage_collector_->GetCumulativeCpuUse();
798 version_cumulative_cpu_use_->Add(
799 (cpu_use - latest_cpu_use_microseconds_).InMilliseconds());
800 latest_cpu_use_microseconds_ = cpu_use;
Daniel Eratc83975a2014-04-04 08:53:44 -0700801 last_update_stats_time_ = now_ticks;
802
803 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
804 const int day = since_epoch.InDays();
805 const int week = day / 7;
806
807 if (daily_cycle_->Get() != day) {
808 daily_cycle_->Set(day);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700809 SendAndResetDailyUseSample(daily_active_use_);
810 SendAndResetCrashFrequencySample(any_crashes_daily_count_);
811 SendAndResetCrashFrequencySample(user_crashes_daily_count_);
812 SendAndResetCrashFrequencySample(kernel_crashes_daily_count_);
813 SendAndResetCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700814 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -0700815 }
816
817 if (weekly_cycle_->Get() != week) {
818 weekly_cycle_->Set(week);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700819 SendAndResetCrashFrequencySample(any_crashes_weekly_count_);
820 SendAndResetCrashFrequencySample(user_crashes_weekly_count_);
821 SendAndResetCrashFrequencySample(kernel_crashes_weekly_count_);
822 SendAndResetCrashFrequencySample(unclean_shutdowns_weekly_count_);
Daniel Eratc83975a2014-04-04 08:53:44 -0700823 }
824}
825
Steve Funge86591e2014-12-01 13:38:21 -0800826void MetricsDaemon::HandleUpdateStatsTimeout() {
827 UpdateStats(TimeTicks::Now(), Time::Now());
828 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
829 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
830 base::Unretained(this)),
831 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -0700832}