blob: 3b81cf824ad7246ad01a1d9fc24fad87ca5ab5bd [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
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080019#include <fcntl.h>
Luigi Semenzato4a6c9422014-06-30 18:12:28 -070020#include <inttypes.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -070021#include <math.h>
Ken Mixter4c5daa42010-08-26 18:35:06 -070022#include <string.h>
Steve Funge86591e2014-12-01 13:38:21 -080023#include <sysexits.h>
Luigi Semenzato8accd332011-05-17 16:37:18 -070024#include <time.h>
Darin Petkov65b01462010-04-14 13:32:20 -070025
Bertrand SIMONNET4b915ae2015-07-28 15:38:14 -070026#include <base/bind.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080027#include <base/files/file_path.h>
Ben Chan51bf92a2014-09-05 08:21:06 -070028#include <base/files/file_util.h>
Luigi Semenzato859b3f02014-02-05 15:33:19 -080029#include <base/hash.h>
Darin Petkov65b01462010-04-14 13:32:20 -070030#include <base/logging.h>
Ben Chan2e6543d2014-02-05 23:26:25 -080031#include <base/strings/string_number_conversions.h>
32#include <base/strings/string_split.h>
33#include <base/strings/string_util.h>
34#include <base/strings/stringprintf.h>
Bertrand SIMONNET26993622015-08-20 14:08:41 -070035#include <cutils/properties.h>
Steve Funge86591e2014-12-01 13:38:21 -080036#include <dbus/dbus.h>
37#include <dbus/message.h>
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -070038
39#include "constants.h"
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -070040#include "uploader/upload_service.h"
Darin Petkov65b01462010-04-14 13:32:20 -070041
Ben Chan2e6543d2014-02-05 23:26:25 -080042using base::FilePath;
43using base::StringPrintf;
Darin Petkovf27f0362010-06-04 13:14:19 -070044using base::Time;
45using base::TimeDelta;
46using base::TimeTicks;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080047using chromeos_metrics::PersistentInteger;
Luigi Semenzato8accd332011-05-17 16:37:18 -070048using std::map;
Darin Petkov38d5cb02010-06-24 12:10:26 -070049using std::string;
Luigi Semenzato8accd332011-05-17 16:37:18 -070050using std::vector;
51
Daniel Eratc83975a2014-04-04 08:53:44 -070052namespace {
Darin Petkovf27f0362010-06-04 13:14:19 -070053
Daniel Eratc83975a2014-04-04 08:53:44 -070054const char kCrashReporterInterface[] = "org.chromium.CrashReporter";
55const char kCrashReporterUserCrashSignal[] = "UserCrash";
Steve Funge86591e2014-12-01 13:38:21 -080056const char kCrashReporterMatchRule[] =
57 "type='signal',interface='%s',path='/',member='%s'";
Darin Petkov41e06232010-05-03 16:45:37 -070058
Daniel Eratc83975a2014-04-04 08:53:44 -070059const int kSecondsPerMinute = 60;
60const int kMinutesPerHour = 60;
61const int kHoursPerDay = 24;
62const int kMinutesPerDay = kHoursPerDay * kMinutesPerHour;
63const int kSecondsPerDay = kSecondsPerMinute * kMinutesPerDay;
64const int kDaysPerWeek = 7;
65const int kSecondsPerWeek = kSecondsPerDay * kDaysPerWeek;
Darin Petkov41e06232010-05-03 16:45:37 -070066
Daniel Eratc83975a2014-04-04 08:53:44 -070067// Interval between calls to UpdateStats().
Steve Funge86591e2014-12-01 13:38:21 -080068const uint32_t kUpdateStatsIntervalMs = 300000;
Darin Petkov65b01462010-04-14 13:32:20 -070069
Luigi Semenzatoc5a92342014-02-14 15:05:51 -080070const char kKernelCrashDetectedFile[] = "/var/run/kernel-crash-detected";
Daniel Eratc83975a2014-04-04 08:53:44 -070071const char kUncleanShutdownDetectedFile[] =
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080072 "/var/run/unclean-shutdown-detected";
Ken Mixterccd84c02010-08-16 19:57:13 -070073
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080074// disk stats metrics
75
76// The {Read,Write}Sectors numbers are in sectors/second.
77// A sector is usually 512 bytes.
78
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -070079const char kMetricReadSectorsLongName[] = "Platform.ReadSectors.PerMinute";
80const char kMetricWriteSectorsLongName[] = "Platform.WriteSectors.PerMinute";
81const char kMetricReadSectorsShortName[] = "Platform.ReadSectors.PerSecond";
82const char kMetricWriteSectorsShortName[] = "Platform.WriteSectors.PerSecond";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080083
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070084const int kMetricStatsShortInterval = 1; // seconds
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -070085const int kMetricStatsLongInterval = 60; // seconds
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080086
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -070087const int kMetricMeminfoInterval = 30; // seconds
88
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080089// Assume a max rate of 250Mb/s for reads (worse for writes) and 512 byte
90// sectors.
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070091const int kMetricSectorsIOMax = 500000; // sectors/second
92const int kMetricSectorsBuckets = 50; // buckets
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070093// Page size is 4k, sector size is 0.5k. We're not interested in page fault
94// rates that the disk cannot sustain.
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070095const int kMetricPageFaultsMax = kMetricSectorsIOMax / 8;
96const int kMetricPageFaultsBuckets = 50;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -070097
98// Major page faults, i.e. the ones that require data to be read from disk.
99
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -0700100const char kMetricPageFaultsLongName[] = "Platform.PageFaults.PerMinute";
101const char kMetricPageFaultsShortName[] = "Platform.PageFaults.PerSecond";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800102
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700103// Swap in and Swap out
104
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -0700105const char kMetricSwapInLongName[] = "Platform.SwapIn.PerMinute";
106const char kMetricSwapInShortName[] = "Platform.SwapIn.PerSecond";
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700107
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -0700108const char kMetricSwapOutLongName[] = "Platform.SwapOut.PerMinute";
109const char kMetricSwapOutShortName[] = "Platform.SwapOut.PerSecond";
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700110
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700111const char kMetricsProcStatFileName[] = "/proc/stat";
112const char kVmStatFileName[] = "/proc/vmstat";
113const char kMeminfoFileName[] = "/proc/meminfo";
114const int kMetricsProcStatFirstLineItemsCount = 11;
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700115const int kDiskMetricsStatItemCount = 11;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700116
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700117// Thermal CPU throttling.
118
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700119const char kMetricScaledCpuFrequencyName[] =
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700120 "Platform.CpuFrequencyThermalScaling";
121
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700122} // namespace
123
Luigi Semenzato96360192014-06-04 10:53:35 -0700124// Zram sysfs entries.
125
126const char MetricsDaemon::kComprDataSizeName[] = "compr_data_size";
127const char MetricsDaemon::kOrigDataSizeName[] = "orig_data_size";
128const char MetricsDaemon::kZeroPagesName[] = "zero_pages";
129
Luigi Semenzato8accd332011-05-17 16:37:18 -0700130// Memory use stats collection intervals. We collect some memory use interval
131// at these intervals after boot, and we stop collecting after the last one,
132// with the assumption that in most cases the memory use won't change much
133// after that.
134static const int kMemuseIntervals[] = {
135 1 * kSecondsPerMinute, // 1 minute mark
136 4 * kSecondsPerMinute, // 5 minute mark
137 25 * kSecondsPerMinute, // 0.5 hour mark
138 120 * kSecondsPerMinute, // 2.5 hour mark
139 600 * kSecondsPerMinute, // 12.5 hour mark
140};
141
Darin Petkovf1e85e42010-06-10 15:59:53 -0700142MetricsDaemon::MetricsDaemon()
Steve Funge86591e2014-12-01 13:38:21 -0800143 : memuse_final_time_(0),
Luigi Semenzato8accd332011-05-17 16:37:18 -0700144 memuse_interval_index_(0),
145 read_sectors_(0),
146 write_sectors_(0),
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700147 vmstats_(),
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700148 stats_state_(kStatsShort),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700149 stats_initial_time_(0),
150 ticks_per_second_(0),
151 latest_cpu_use_ticks_(0) {}
Darin Petkovf1e85e42010-06-10 15:59:53 -0700152
Ken Mixter4c5daa42010-08-26 18:35:06 -0700153MetricsDaemon::~MetricsDaemon() {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700154}
155
Luigi Semenzato8accd332011-05-17 16:37:18 -0700156double MetricsDaemon::GetActiveTime() {
157 struct timespec ts;
158 int r = clock_gettime(CLOCK_MONOTONIC, &ts);
159 if (r < 0) {
160 PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
161 return 0;
162 } else {
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700163 return ts.tv_sec + static_cast<double>(ts.tv_nsec) / (1000 * 1000 * 1000);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700164 }
165}
166
Steve Funge86591e2014-12-01 13:38:21 -0800167int MetricsDaemon::Run() {
Ken Mixterccd84c02010-08-16 19:57:13 -0700168 if (CheckSystemCrash(kKernelCrashDetectedFile)) {
169 ProcessKernelCrash();
170 }
171
172 if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
173 ProcessUncleanShutdown();
174 }
175
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800176 // On OS version change, clear version stats (which are reported daily).
Ben Chanf05ab402014-08-07 00:54:59 -0700177 int32_t version = GetOsVersionHash();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800178 if (version_cycle_->Get() != version) {
179 version_cycle_->Set(version);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800180 kernel_crashes_version_count_->Set(0);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700181 version_cumulative_active_use_->Set(0);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700182 version_cumulative_cpu_use_->Set(0);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800183 }
184
Steve Funge86591e2014-12-01 13:38:21 -0800185 return chromeos::DBusDaemon::Run();
Darin Petkov65b01462010-04-14 13:32:20 -0700186}
187
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700188void MetricsDaemon::RunUploaderTest() {
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700189 upload_service_.reset(new UploadService(
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700190 new SystemProfileCache(true, metrics_directory_),
Bertrand SIMONNET12531862015-08-31 11:11:57 -0700191 metrics_lib_,
192 server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700193 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700194 upload_service_->UploadEvent();
195}
196
Ben Chanf05ab402014-08-07 00:54:59 -0700197uint32_t MetricsDaemon::GetOsVersionHash() {
198 static uint32_t cached_version_hash = 0;
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800199 static bool version_hash_is_cached = false;
200 if (version_hash_is_cached)
201 return cached_version_hash;
202 version_hash_is_cached = true;
Bertrand SIMONNET26993622015-08-20 14:08:41 -0700203
204 char version[PROPERTY_VALUE_MAX];
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700205 // The version might not be set for development devices. In this case, use the
206 // zero version.
Bertrand SIMONNET26993622015-08-20 14:08:41 -0700207 property_get(metrics::kProductVersionProperty, version,
208 metrics::kDefaultVersion);
209
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700210 cached_version_hash = base::Hash(version);
211 if (testing_) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800212 cached_version_hash = 42; // return any plausible value for the hash
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800213 }
214 return cached_version_hash;
215}
216
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700217void MetricsDaemon::Init(bool testing,
218 bool uploader_active,
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700219 bool dbus_enabled,
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700220 MetricsLibraryInterface* metrics_lib,
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700221 const string& diskstats_path,
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700222 const string& scaling_max_freq_path,
Steve Fung67906c62014-10-06 15:15:30 -0700223 const string& cpuinfo_max_freq_path,
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700224 const base::TimeDelta& upload_interval,
Steve Fung67906c62014-10-06 15:15:30 -0700225 const string& server,
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700226 const base::FilePath& metrics_directory) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700227 CHECK(metrics_lib);
Darin Petkov65b01462010-04-14 13:32:20 -0700228 testing_ = testing;
Steve Funge86591e2014-12-01 13:38:21 -0800229 uploader_active_ = uploader_active;
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700230 dbus_enabled_ = dbus_enabled;
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700231 metrics_directory_ = metrics_directory;
Darin Petkovfc91b422010-05-12 13:05:45 -0700232 metrics_lib_ = metrics_lib;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700233
Bertrand SIMONNETcac74e12014-10-09 10:14:13 -0700234 upload_interval_ = upload_interval;
Steve Fung67906c62014-10-06 15:15:30 -0700235 server_ = server;
Steve Fung67906c62014-10-06 15:15:30 -0700236
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700237 // Get ticks per second (HZ) on this system.
238 // Sysconf cannot fail, so no sanity checks are needed.
239 ticks_per_second_ = sysconf(_SC_CLK_TCK);
240
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700241 daily_active_use_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700242 new PersistentInteger("Platform.UseTime.PerDay"));
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -0700243 version_cumulative_active_use_.reset(
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700244 new PersistentInteger("Platform.CumulativeUseTime"));
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700245 version_cumulative_cpu_use_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700246 new PersistentInteger("Platform.CumulativeCpuTime"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700247
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800248 kernel_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700249 new PersistentInteger("Platform.KernelCrashInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800250 unclean_shutdown_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700251 new PersistentInteger("Platform.UncleanShutdownInterval"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800252 user_crash_interval_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700253 new PersistentInteger("Platform.UserCrashInterval"));
Darin Petkov2ccef012010-05-05 16:06:37 -0700254
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800255 any_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700256 new PersistentInteger("Platform.AnyCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800257 any_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700258 new PersistentInteger("Platform.AnyCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800259 user_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700260 new PersistentInteger("Platform.UserCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800261 user_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700262 new PersistentInteger("Platform.UserCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800263 kernel_crashes_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700264 new PersistentInteger("Platform.KernelCrashes.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800265 kernel_crashes_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700266 new PersistentInteger("Platform.KernelCrashes.PerWeek"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800267 kernel_crashes_version_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700268 new PersistentInteger("Platform.KernelCrashesSinceUpdate"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800269 unclean_shutdowns_daily_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700270 new PersistentInteger("Platform.UncleanShutdown.PerDay"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800271 unclean_shutdowns_weekly_count_.reset(
Bertrand SIMONNET5066a452015-09-25 15:38:42 -0700272 new PersistentInteger("Platform.UncleanShutdowns.PerWeek"));
Darin Petkov38d5cb02010-06-24 12:10:26 -0700273
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800274 daily_cycle_.reset(new PersistentInteger("daily.cycle"));
275 weekly_cycle_.reset(new PersistentInteger("weekly.cycle"));
276 version_cycle_.reset(new PersistentInteger("version.cycle"));
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800277
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700278 diskstats_path_ = diskstats_path;
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700279 scaling_max_freq_path_ = scaling_max_freq_path;
280 cpuinfo_max_freq_path_ = cpuinfo_max_freq_path;
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700281 disk_usage_collector_.reset(new DiskUsageCollector(metrics_lib_));
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700282
283 // If testing, initialize Stats Reporter without connecting DBus
284 if (testing_)
285 StatsReporterInit();
Steve Funge86591e2014-12-01 13:38:21 -0800286}
287
288int MetricsDaemon::OnInit() {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700289 int return_code = dbus_enabled_ ? chromeos::DBusDaemon::OnInit() :
290 chromeos::Daemon::OnInit();
Steve Funge86591e2014-12-01 13:38:21 -0800291 if (return_code != EX_OK)
292 return return_code;
293
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700294 StatsReporterInit();
295
296 // Start collecting meminfo stats.
297 ScheduleMeminfoCallback(kMetricMeminfoInterval);
298 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
299 ScheduleMemuseCallback(kMemuseIntervals[0]);
300
Steve Funge86591e2014-12-01 13:38:21 -0800301 if (testing_)
302 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700303
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700304 if (dbus_enabled_) {
305 bus_->AssertOnDBusThread();
306 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700307
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700308 if (bus_->is_connected()) {
309 const std::string match_rule =
310 base::StringPrintf(kCrashReporterMatchRule,
311 kCrashReporterInterface,
312 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700313
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700314 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700315
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700316 DBusError error;
317 dbus_error_init(&error);
318 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700319
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700320 if (dbus_error_is_set(&error)) {
321 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
322 << error.name << ": " << error.message;
323 return EX_SOFTWARE;
324 }
325 } else {
326 LOG(ERROR) << "DBus isn't connected.";
327 return EX_UNAVAILABLE;
Steve Funge86591e2014-12-01 13:38:21 -0800328 }
Darin Petkov703ec972010-04-27 11:02:18 -0700329 }
330
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700331 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
332 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
333 base::Unretained(this)),
334 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
335
Steve Funge86591e2014-12-01 13:38:21 -0800336 if (uploader_active_) {
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700337 upload_service_.reset(
338 new UploadService(new SystemProfileCache(), metrics_lib_, server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700339 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700340 }
Steve Funge86591e2014-12-01 13:38:21 -0800341
342 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700343}
344
Steve Funge86591e2014-12-01 13:38:21 -0800345void MetricsDaemon::OnShutdown(int* return_code) {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700346 if (!testing_ && dbus_enabled_ && bus_->is_connected()) {
Steve Funge86591e2014-12-01 13:38:21 -0800347 const std::string match_rule =
348 base::StringPrintf(kCrashReporterMatchRule,
349 kCrashReporterInterface,
350 kCrashReporterUserCrashSignal);
351
352 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
353
354 DBusError error;
355 dbus_error_init(&error);
356 bus_->RemoveMatch(match_rule, &error);
357
358 if (dbus_error_is_set(&error)) {
359 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
360 << error.name << ": " << error.message;
361 }
362 }
363 chromeos::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700364}
365
Darin Petkov703ec972010-04-27 11:02:18 -0700366// static
367DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
368 DBusMessage* message,
369 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700370 int message_type = dbus_message_get_type(message);
371 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700372 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700373 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
374 }
375
376 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700377 const std::string interface(dbus_message_get_interface(message));
378 const std::string member(dbus_message_get_member(message));
379 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700380
381 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
382
383 DBusMessageIter iter;
384 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700385 if (interface == kCrashReporterInterface) {
386 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700387 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700388 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700389 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700390 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
391 }
392
393 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700394}
395
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700396// One might argue that parts of this should go into
397// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
398
399TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700400 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
401 std::string proc_stat_string;
402 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
403 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
404 return TimeDelta();
405 }
406
407 std::vector<std::string> proc_stat_lines;
408 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
409 if (proc_stat_lines.empty()) {
410 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
411 << ": " << proc_stat_string;
412 return TimeDelta();
413 }
414 std::vector<std::string> proc_stat_totals;
415 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
416
Ben Chanf05ab402014-08-07 00:54:59 -0700417 uint64_t user_ticks, user_nice_ticks, system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700418 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
419 proc_stat_totals[0] != "cpu" ||
420 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
421 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
422 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
423 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
424 return TimeDelta(base::TimeDelta::FromSeconds(0));
425 }
426
Ben Chanf05ab402014-08-07 00:54:59 -0700427 uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700428
429 // Sanity check.
430 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
431 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
432 << " to " << total_cpu_use_ticks;
433 return TimeDelta();
434 }
435
Ben Chanf05ab402014-08-07 00:54:59 -0700436 uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700437 latest_cpu_use_ticks_ = total_cpu_use_ticks;
438 // Use microseconds to avoid significant truncations.
439 return base::TimeDelta::FromMicroseconds(
440 diff * 1000 * 1000 / ticks_per_second_);
441}
442
Darin Petkov1bb904e2010-06-16 15:58:06 -0700443void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700444 // Counts the active time up to now.
445 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700446
447 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700448 SendAndResetCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700449
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800450 any_crashes_daily_count_->Add(1);
451 any_crashes_weekly_count_->Add(1);
452 user_crashes_daily_count_->Add(1);
453 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700454}
455
Darin Petkov38d5cb02010-06-24 12:10:26 -0700456void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700457 // Counts the active time up to now.
458 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700459
460 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700461 SendAndResetCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700462
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800463 any_crashes_daily_count_->Add(1);
464 any_crashes_weekly_count_->Add(1);
465 kernel_crashes_daily_count_->Add(1);
466 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800467
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800468 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700469}
470
Ken Mixterccd84c02010-08-16 19:57:13 -0700471void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700472 // Counts the active time up to now.
473 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700474
475 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700476 SendAndResetCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700477
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800478 unclean_shutdowns_daily_count_->Add(1);
479 unclean_shutdowns_weekly_count_->Add(1);
480 any_crashes_daily_count_->Add(1);
481 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700482}
483
Luigi Semenzato8accd332011-05-17 16:37:18 -0700484bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700485 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800486 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700487 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700488
489 // Deletes the crash-detected file so that the daemon doesn't report
490 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800491 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700492 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700493}
494
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700495void MetricsDaemon::StatsReporterInit() {
Bertrand SIMONNET5658dc52015-09-18 13:38:10 -0700496 disk_usage_collector_->Schedule();
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800497 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700498 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800499 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700500 stats_state_ = kStatsLong;
501 stats_initial_time_ = GetActiveTime();
502 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700503 LOG(WARNING) << "not collecting disk stats";
504 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700505 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700506 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800507}
508
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700509void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800510 if (testing_) {
511 return;
512 }
Steve Funge86591e2014-12-01 13:38:21 -0800513 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
514 base::Bind(&MetricsDaemon::StatsCallback, base::Unretained(this)),
515 base::TimeDelta::FromSeconds(wait));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800516}
517
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700518bool MetricsDaemon::DiskStatsReadStats(uint64_t* read_sectors,
519 uint64_t* write_sectors) {
520 CHECK(read_sectors);
521 CHECK(write_sectors);
522 std::string line;
523 if (diskstats_path_.empty()) {
524 return false;
525 }
526
527 if (!base::ReadFileToString(base::FilePath(diskstats_path_), &line)) {
528 PLOG(WARNING) << "Could not read disk stats from " << diskstats_path_;
529 return false;
530 }
531
532 std::vector<std::string> parts = base::SplitString(
533 line, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
534 if (parts.size() != kDiskMetricsStatItemCount) {
535 LOG(ERROR) << "Could not parse disk stat correctly. Expected "
536 << kDiskMetricsStatItemCount << " elements but got "
537 << parts.size();
538 return false;
539 }
540 if (!base::StringToUint64(parts[2], read_sectors)) {
541 LOG(ERROR) << "Couldn't convert read sectors " << parts[2] << " to uint64";
542 return false;
543 }
544 if (!base::StringToUint64(parts[6], write_sectors)) {
545 LOG(ERROR) << "Couldn't convert write sectors " << parts[6] << " to uint64";
546 return false;
547 }
548
549 return true;
550}
551
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700552bool MetricsDaemon::VmStatsParseStats(const char* stats,
553 struct VmstatRecord* record) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700554 CHECK(stats);
555 CHECK(record);
556 base::StringPairs pairs;
557 base::SplitStringIntoKeyValuePairs(stats, ' ', '\n', &pairs);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700558
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700559 for (base::StringPairs::iterator it = pairs.begin(); it != pairs.end(); ++it) {
560 if (it->first == "pgmajfault" &&
561 !base::StringToUint64(it->second, &record->page_faults_)) {
562 return false;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700563 }
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700564 if (it->first == "pswpin" &&
565 !base::StringToUint64(it->second, &record->swap_in_)) {
566 return false;
567 }
568 if (it->first == "pswpout" &&
569 !base::StringToUint64(it->second, &record->swap_out_)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700570 return false;
571 }
572 }
573 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700574}
575
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700576bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700577 CHECK(stats);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700578 string value_string;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700579 if (!base::ReadFileToString(base::FilePath(kVmStatFileName), &value_string)) {
580 LOG(WARNING) << "cannot read " << kVmStatFileName;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700581 return false;
582 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700583 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800584}
585
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700586bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700587 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700588 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800589 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700590 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
591 return false;
592 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800593 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700594 LOG(WARNING) << "no newline in " << value_string;
595 // Continue even though the lack of newline is suspicious.
596 }
597 if (!base::StringToInt(value_string, value)) {
598 LOG(WARNING) << "cannot convert " << value_string << " to int";
599 return false;
600 }
601 return true;
602}
603
604void MetricsDaemon::SendCpuThrottleMetrics() {
605 // |max_freq| is 0 only the first time through.
606 static int max_freq = 0;
607 if (max_freq == -1)
608 // Give up, as sysfs did not report max_freq correctly.
609 return;
610 if (max_freq == 0 || testing_) {
611 // One-time initialization of max_freq. (Every time when testing.)
612 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
613 max_freq = -1;
614 return;
615 }
616 if (max_freq == 0) {
617 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
618 max_freq = -1;
619 return;
620 }
621 if (max_freq % 10000 == 1000) {
622 // Special case: system has turbo mode, and max non-turbo frequency is
623 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
624 // being multiples of (at least) 10 MHz. Although there is no guarantee
625 // of this, it seems a fairly reasonable assumption. Otherwise we should
626 // read scaling_available_frequencies, sort the frequencies, compare the
627 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
628 // hack too, no telling when it will change).
629 max_freq -= 1000;
630 }
631 }
632 int scaled_freq = 0;
633 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
634 return;
635 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
636 // scaled_freq is not the actual turbo frequency. We indicate this situation
637 // with a 101% value.
638 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800639 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700640}
641
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700642// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700643
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700644void MetricsDaemon::StatsCallback() {
Ben Chanf05ab402014-08-07 00:54:59 -0700645 uint64_t read_sectors_now, write_sectors_now;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700646 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700647 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700648 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700649 if (testing_) {
650 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700651 delta_time = stats_state_ == kStatsShort ?
652 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700653 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700654 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
655 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700656 int delta_read = read_sectors_now - read_sectors_;
657 int delta_write = write_sectors_now - write_sectors_;
658 int read_sectors_per_second = delta_read / delta_time;
659 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700660 bool vmstats_success = VmStatsReadStats(&vmstats_now);
661 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
662 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
663 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
664 uint64_t page_faults_per_second = delta_faults / delta_time;
665 uint64_t swap_in_per_second = delta_swap_in / delta_time;
666 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800667
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700668 switch (stats_state_) {
669 case kStatsShort:
670 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800671 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700672 read_sectors_per_second,
673 1,
674 kMetricSectorsIOMax,
675 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800676 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700677 write_sectors_per_second,
678 1,
679 kMetricSectorsIOMax,
680 kMetricSectorsBuckets);
681 }
682 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800683 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700684 page_faults_per_second,
685 1,
686 kMetricPageFaultsMax,
687 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800688 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700689 swap_in_per_second,
690 1,
691 kMetricPageFaultsMax,
692 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800693 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700694 swap_out_per_second,
695 1,
696 kMetricPageFaultsMax,
697 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700698 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800699 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700700 stats_state_ = kStatsLong;
701 ScheduleStatsCallback(kMetricStatsLongInterval -
702 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800703 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700704 case kStatsLong:
705 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800706 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700707 read_sectors_per_second,
708 1,
709 kMetricSectorsIOMax,
710 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800711 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700712 write_sectors_per_second,
713 1,
714 kMetricSectorsIOMax,
715 kMetricSectorsBuckets);
716 // Reset sector counters.
717 read_sectors_ = read_sectors_now;
718 write_sectors_ = write_sectors_now;
719 }
720 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800721 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700722 page_faults_per_second,
723 1,
724 kMetricPageFaultsMax,
725 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800726 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700727 swap_in_per_second,
728 1,
729 kMetricPageFaultsMax,
730 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800731 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700732 swap_out_per_second,
733 1,
734 kMetricPageFaultsMax,
735 kMetricPageFaultsBuckets);
736
737 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700738 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700739 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700740 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700741 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800742 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700743 stats_state_ = kStatsShort;
744 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800745 break;
746 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700747 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800748 }
749}
750
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700751void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
752 if (testing_) {
753 return;
754 }
Steve Funge86591e2014-12-01 13:38:21 -0800755 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
756 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
757 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800758 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800759 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700760}
761
Steve Funge86591e2014-12-01 13:38:21 -0800762void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700763 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700764 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800765 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700766 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800767 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700768 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700769 // Make both calls even if the first one fails.
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700770 if (ProcessMeminfo(meminfo_raw)) {
Steve Funge86591e2014-12-01 13:38:21 -0800771 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
772 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800773 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800774 wait);
775 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700776}
777
778// static
779bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700780 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700781 std::string content;
782 if (!base::ReadFileToString(path, &content)) {
783 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
784 return false;
785 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700786 // Remove final newline.
787 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700788 if (!base::StringToUint64(content, value)) {
789 LOG(WARNING) << "invalid integer: " << content;
790 return false;
791 }
792 return true;
793}
794
795bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
796 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700797 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700798 const size_t page_size = 4096;
799
800 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
801 &compr_data_size) ||
802 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
803 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
804 return false;
805 }
806
807 // |orig_data_size| does not include zero-filled pages.
808 orig_data_size += zero_pages * page_size;
809
810 const int compr_data_size_mb = compr_data_size >> 20;
811 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
812 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
813
814 // Report compressed size in megabytes. 100 MB or less has little impact.
815 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
816 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
817 // The compression ratio is multiplied by 100 for better resolution. The
818 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
819 // don't want samples when very little memory is being compressed.
820 if (compr_data_size_mb >= 1) {
821 SendSample("Platform.ZramCompressionRatioPercent",
822 orig_data_size * 100 / compr_data_size, 100, 600, 50);
823 }
824 // The values of interest for zero_pages are between 1MB and 1GB. The units
825 // are number of pages.
826 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
827 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
828
829 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700830}
831
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700832bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700833 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700834 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
835 { "MemFree", "MemFree" },
836 { "Buffers", "Buffers" },
837 { "Cached", "Cached" },
838 // { "SwapCached", "SwapCached" },
839 { "Active", "Active" },
840 { "Inactive", "Inactive" },
841 { "ActiveAnon", "Active(anon)" },
842 { "InactiveAnon", "Inactive(anon)" },
843 { "ActiveFile" , "Active(file)" },
844 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800845 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700846 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800847 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
848 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700849 // { "Dirty", "Dirty" },
850 // { "Writeback", "Writeback" },
851 { "AnonPages", "AnonPages" },
852 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800853 { "Shmem", "Shmem", kMeminfoOp_HistLog },
854 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700855 // { "SReclaimable", "SReclaimable" },
856 // { "SUnreclaim", "SUnreclaim" },
857 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700858 vector<MeminfoRecord> fields(fields_array,
859 fields_array + arraysize(fields_array));
860 if (!FillMeminfo(meminfo_raw, &fields)) {
861 return false;
862 }
863 int total_memory = fields[0].value;
864 if (total_memory == 0) {
865 // this "cannot happen"
866 LOG(WARNING) << "borked meminfo parser";
867 return false;
868 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800869 int swap_total = 0;
870 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700871 // Send all fields retrieved, except total memory.
872 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800873 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
874 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800875 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800876 switch (fields[i].op) {
877 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800878 // report value as percent of total memory
879 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800880 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800881 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800882 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800883 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800884 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800885 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800886 case kMeminfoOp_SwapTotal:
887 swap_total = fields[i].value;
888 case kMeminfoOp_SwapFree:
889 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800890 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700891 }
892 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800893 if (swap_total > 0) {
894 int swap_used = swap_total - swap_free;
895 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800896 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
Bertrand SIMONNET008fb7e2015-09-21 16:48:01 -0700897 SendLinearSample("Platform.MeminfoSwapUsed.Percent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800898 100, 101);
899 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700900 return true;
901}
902
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700903bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
904 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700905 vector<string> lines;
906 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700907
908 // Scan meminfo output and collect field values. Each field name has to
909 // match a meminfo entry (case insensitive) after removing non-alpha
910 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700911 unsigned int ifield = 0;
912 for (unsigned int iline = 0;
913 iline < nlines && ifield < fields->size();
914 iline++) {
915 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700916 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700917 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
918 // Name matches. Parse value and save.
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700919 if (!base::StringToInt(tokens[1], &(*fields)[ifield].value)) {
920 LOG(WARNING) << "Cound not convert " << tokens[1] << " to int";
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700921 return false;
922 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700923 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700924 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700925 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700926 if (ifield < fields->size()) {
927 // End of input reached while scanning.
928 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
929 << " and following";
930 return false;
931 }
932 return true;
933}
934
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800935void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700936 if (testing_) {
937 return;
938 }
Steve Funge86591e2014-12-01 13:38:21 -0800939 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
940 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
941 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700942}
943
944void MetricsDaemon::MemuseCallback() {
945 // Since we only care about active time (i.e. uptime minus sleep time) but
946 // the callbacks are driven by real time (uptime), we check if we should
947 // reschedule this callback due to intervening sleep periods.
948 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800949 // Avoid intervals of less than one second.
950 double remaining_time = ceil(memuse_final_time_ - now);
951 if (remaining_time > 0) {
952 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700953 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800954 // Report stats and advance the measurement interval unless there are
955 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700956 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800957 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
958 double interval = kMemuseIntervals[memuse_interval_index_++];
959 memuse_final_time_ = now + interval;
960 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700961 }
962 }
963}
964
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700965bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700966 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700967 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800968 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700969 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
970 return false;
971 }
972 return ProcessMemuse(meminfo_raw);
973}
974
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700975bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700976 static const MeminfoRecord fields_array[] = {
977 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
978 { "ActiveAnon", "Active(anon)" },
979 { "InactiveAnon", "Inactive(anon)" },
980 };
981 vector<MeminfoRecord> fields(fields_array,
982 fields_array + arraysize(fields_array));
983 if (!FillMeminfo(meminfo_raw, &fields)) {
984 return false;
985 }
986 int total = fields[0].value;
987 int active_anon = fields[1].value;
988 int inactive_anon = fields[2].value;
989 if (total == 0) {
990 // this "cannot happen"
991 LOG(WARNING) << "borked meminfo parser";
992 return false;
993 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800994 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
995 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800996 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -0700997 100, 101);
998 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700999}
1000
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001001void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -07001002 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -07001003 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -07001004}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001005
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001006void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001007 // Report the number of crashes for this OS version, but don't clear the
1008 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -07001009 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001010 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001011 crashes_count,
1012 1, // value of first bucket
1013 500, // value of last bucket
1014 100); // number of buckets
1015
1016
Ben Chanf05ab402014-08-07 00:54:59 -07001017 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001018 SendSample(version_cumulative_cpu_use_->Name(),
1019 cpu_use_ms / 1000, // stat is in seconds
1020 1, // device may be used very little...
1021 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
1022 100);
1023
1024 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
1025 // can be zero. Avoid division by zero.
1026 if (cpu_use_ms > 0) {
1027 // Send the crash frequency since update in number of crashes per CPU year.
1028 SendSample("Logging.KernelCrashesPerCpuYear",
1029 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
1030 1,
1031 1000 * 1000, // about one crash every 30s of CPU time
1032 100);
1033 }
1034
Ben Chanf05ab402014-08-07 00:54:59 -07001035 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001036 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001037 SendSample(version_cumulative_active_use_->Name(),
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001038 active_use_seconds,
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001039 1, // device may be used very little...
1040 8 * 1000 * 1000, // ... or a lot (about 90 days)
1041 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001042 // Same as above, but per year of active time.
1043 SendSample("Logging.KernelCrashesPerActiveYear",
1044 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
1045 1,
1046 1000 * 1000, // about one crash every 30s of active time
1047 100);
1048 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001049}
1050
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001051void MetricsDaemon::SendAndResetDailyUseSample(
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001052 const scoped_ptr<PersistentInteger>& use) {
1053 SendSample(use->Name(),
1054 use->GetAndClear(),
1055 1, // value of first bucket
1056 kSecondsPerDay, // value of last bucket
1057 50); // number of buckets
1058}
1059
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001060void MetricsDaemon::SendAndResetCrashIntervalSample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001061 const scoped_ptr<PersistentInteger>& interval) {
1062 SendSample(interval->Name(),
1063 interval->GetAndClear(),
1064 1, // value of first bucket
1065 4 * kSecondsPerWeek, // value of last bucket
1066 50); // number of buckets
1067}
1068
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001069void MetricsDaemon::SendAndResetCrashFrequencySample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001070 const scoped_ptr<PersistentInteger>& frequency) {
1071 SendSample(frequency->Name(),
1072 frequency->GetAndClear(),
1073 1, // value of first bucket
1074 100, // value of last bucket
1075 50); // number of buckets
1076}
1077
1078void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001079 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001080 // TODO(semenzato): add a proper linear histogram to the Chrome external
1081 // metrics API.
1082 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1083 metrics_lib_->SendEnumToUMA(name, sample, max);
1084}
Daniel Eratc83975a2014-04-04 08:53:44 -07001085
1086void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
1087 Time now_wall_time) {
1088 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001089 daily_active_use_->Add(elapsed_seconds);
1090 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -07001091 user_crash_interval_->Add(elapsed_seconds);
1092 kernel_crash_interval_->Add(elapsed_seconds);
1093 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
1094 last_update_stats_time_ = now_ticks;
1095
1096 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
1097 const int day = since_epoch.InDays();
1098 const int week = day / 7;
1099
1100 if (daily_cycle_->Get() != day) {
1101 daily_cycle_->Set(day);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001102 SendAndResetDailyUseSample(daily_active_use_);
1103 SendAndResetCrashFrequencySample(any_crashes_daily_count_);
1104 SendAndResetCrashFrequencySample(user_crashes_daily_count_);
1105 SendAndResetCrashFrequencySample(kernel_crashes_daily_count_);
1106 SendAndResetCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001107 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -07001108 }
1109
1110 if (weekly_cycle_->Get() != week) {
1111 weekly_cycle_->Set(week);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001112 SendAndResetCrashFrequencySample(any_crashes_weekly_count_);
1113 SendAndResetCrashFrequencySample(user_crashes_weekly_count_);
1114 SendAndResetCrashFrequencySample(kernel_crashes_weekly_count_);
1115 SendAndResetCrashFrequencySample(unclean_shutdowns_weekly_count_);
Daniel Eratc83975a2014-04-04 08:53:44 -07001116 }
1117}
1118
Steve Funge86591e2014-12-01 13:38:21 -08001119void MetricsDaemon::HandleUpdateStatsTimeout() {
1120 UpdateStats(TimeTicks::Now(), Time::Now());
1121 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
1122 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
1123 base::Unretained(this)),
1124 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -07001125}