blob: b0e4b2f6ddae5b9752bc6937d29e900c590b979a [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 SIMONNET675a10c2015-08-25 14:11:43 -070079const char kMetricReadSectorsLongName[] = "Platform.ReadSectorsLong";
80const char kMetricWriteSectorsLongName[] = "Platform.WriteSectorsLong";
81const char kMetricReadSectorsShortName[] = "Platform.ReadSectorsShort";
82const char kMetricWriteSectorsShortName[] = "Platform.WriteSectorsShort";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080083
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -070084const int kMetricStatsShortInterval = 1; // seconds
85const int kMetricStatsLongInterval = 30; // 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 SIMONNET675a10c2015-08-25 14:11:43 -0700100const char kMetricPageFaultsLongName[] = "Platform.PageFaultsLong";
101const char kMetricPageFaultsShortName[] = "Platform.PageFaultsShort";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800102
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700103// Swap in and Swap out
104
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700105const char kMetricSwapInLongName[] = "Platform.SwapInLong";
106const char kMetricSwapInShortName[] = "Platform.SwapInShort";
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700107
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700108const char kMetricSwapOutLongName[] = "Platform.SwapOutLong";
109const char kMetricSwapOutShortName[] = "Platform.SwapOutShort";
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(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700242 new PersistentInteger("Platform.DailyUseTime"));
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(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700256 new PersistentInteger("Platform.AnyCrashesDaily"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800257 any_crashes_weekly_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700258 new PersistentInteger("Platform.AnyCrashesWeekly"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800259 user_crashes_daily_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700260 new PersistentInteger("Platform.UserCrashesDaily"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800261 user_crashes_weekly_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700262 new PersistentInteger("Platform.UserCrashesWeekly"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800263 kernel_crashes_daily_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700264 new PersistentInteger("Platform.KernelCrashesDaily"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800265 kernel_crashes_weekly_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700266 new PersistentInteger("Platform.KernelCrashesWeekly"));
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(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700270 new PersistentInteger("Platform.UncleanShutdownsDaily"));
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800271 unclean_shutdowns_weekly_count_.reset(
Luigi Semenzatodc865892015-07-09 08:28:08 -0700272 new PersistentInteger("Platform.UncleanShutdownsWeekly"));
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 SIMONNETebbe35c2015-09-08 10:13:35 -0700281
282 // If testing, initialize Stats Reporter without connecting DBus
283 if (testing_)
284 StatsReporterInit();
Steve Funge86591e2014-12-01 13:38:21 -0800285}
286
287int MetricsDaemon::OnInit() {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700288 int return_code = dbus_enabled_ ? chromeos::DBusDaemon::OnInit() :
289 chromeos::Daemon::OnInit();
Steve Funge86591e2014-12-01 13:38:21 -0800290 if (return_code != EX_OK)
291 return return_code;
292
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700293 StatsReporterInit();
294
295 // Start collecting meminfo stats.
296 ScheduleMeminfoCallback(kMetricMeminfoInterval);
297 memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
298 ScheduleMemuseCallback(kMemuseIntervals[0]);
299
Steve Funge86591e2014-12-01 13:38:21 -0800300 if (testing_)
301 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700302
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700303 if (dbus_enabled_) {
304 bus_->AssertOnDBusThread();
305 CHECK(bus_->SetUpAsyncOperations());
Darin Petkov65b01462010-04-14 13:32:20 -0700306
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700307 if (bus_->is_connected()) {
308 const std::string match_rule =
309 base::StringPrintf(kCrashReporterMatchRule,
310 kCrashReporterInterface,
311 kCrashReporterUserCrashSignal);
Darin Petkov65b01462010-04-14 13:32:20 -0700312
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700313 bus_->AddFilterFunction(&MetricsDaemon::MessageFilter, this);
Darin Petkov65b01462010-04-14 13:32:20 -0700314
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700315 DBusError error;
316 dbus_error_init(&error);
317 bus_->AddMatch(match_rule, &error);
Darin Petkov65b01462010-04-14 13:32:20 -0700318
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700319 if (dbus_error_is_set(&error)) {
320 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
321 << error.name << ": " << error.message;
322 return EX_SOFTWARE;
323 }
324 } else {
325 LOG(ERROR) << "DBus isn't connected.";
326 return EX_UNAVAILABLE;
Steve Funge86591e2014-12-01 13:38:21 -0800327 }
Darin Petkov703ec972010-04-27 11:02:18 -0700328 }
329
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700330 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
331 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
332 base::Unretained(this)),
333 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
334
Steve Funge86591e2014-12-01 13:38:21 -0800335 if (uploader_active_) {
Bertrand SIMONNETbae5dcc2015-08-04 14:12:10 -0700336 upload_service_.reset(
337 new UploadService(new SystemProfileCache(), metrics_lib_, server_));
Bertrand SIMONNET2765d0a2015-09-09 10:38:20 -0700338 upload_service_->Init(upload_interval_, metrics_directory_);
Bertrand SIMONNET46b49da2014-06-25 14:38:07 -0700339 }
Steve Funge86591e2014-12-01 13:38:21 -0800340
341 return EX_OK;
Darin Petkov65b01462010-04-14 13:32:20 -0700342}
343
Steve Funge86591e2014-12-01 13:38:21 -0800344void MetricsDaemon::OnShutdown(int* return_code) {
Bertrand SIMONNETfec4d2c2015-08-05 16:04:14 -0700345 if (!testing_ && dbus_enabled_ && bus_->is_connected()) {
Steve Funge86591e2014-12-01 13:38:21 -0800346 const std::string match_rule =
347 base::StringPrintf(kCrashReporterMatchRule,
348 kCrashReporterInterface,
349 kCrashReporterUserCrashSignal);
350
351 bus_->RemoveFilterFunction(&MetricsDaemon::MessageFilter, this);
352
353 DBusError error;
354 dbus_error_init(&error);
355 bus_->RemoveMatch(match_rule, &error);
356
357 if (dbus_error_is_set(&error)) {
358 LOG(ERROR) << "Failed to remove match rule \"" << match_rule << "\". Got "
359 << error.name << ": " << error.message;
360 }
361 }
362 chromeos::DBusDaemon::OnShutdown(return_code);
Darin Petkov65b01462010-04-14 13:32:20 -0700363}
364
Darin Petkov703ec972010-04-27 11:02:18 -0700365// static
366DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
367 DBusMessage* message,
368 void* user_data) {
Darin Petkov703ec972010-04-27 11:02:18 -0700369 int message_type = dbus_message_get_type(message);
370 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700371 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700372 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
373 }
374
375 // Signal messages always have interfaces.
Daniel Eratc83975a2014-04-04 08:53:44 -0700376 const std::string interface(dbus_message_get_interface(message));
377 const std::string member(dbus_message_get_member(message));
378 DLOG(INFO) << "Got " << interface << "." << member << " D-Bus signal";
Darin Petkov703ec972010-04-27 11:02:18 -0700379
380 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
381
382 DBusMessageIter iter;
383 dbus_message_iter_init(message, &iter);
Daniel Eratc83975a2014-04-04 08:53:44 -0700384 if (interface == kCrashReporterInterface) {
385 CHECK_EQ(member, kCrashReporterUserCrashSignal);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700386 daemon->ProcessUserCrash();
Darin Petkov703ec972010-04-27 11:02:18 -0700387 } else {
Daniel Eratc83975a2014-04-04 08:53:44 -0700388 // Ignore messages from the bus itself.
Darin Petkov703ec972010-04-27 11:02:18 -0700389 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
390 }
391
392 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700393}
394
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700395// One might argue that parts of this should go into
396// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
397
398TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700399 FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
400 std::string proc_stat_string;
401 if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
402 LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
403 return TimeDelta();
404 }
405
406 std::vector<std::string> proc_stat_lines;
407 base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
408 if (proc_stat_lines.empty()) {
409 LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
410 << ": " << proc_stat_string;
411 return TimeDelta();
412 }
413 std::vector<std::string> proc_stat_totals;
414 base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
415
Ben Chanf05ab402014-08-07 00:54:59 -0700416 uint64_t user_ticks, user_nice_ticks, system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700417 if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
418 proc_stat_totals[0] != "cpu" ||
419 !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
420 !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
421 !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
422 LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
423 return TimeDelta(base::TimeDelta::FromSeconds(0));
424 }
425
Ben Chanf05ab402014-08-07 00:54:59 -0700426 uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700427
428 // Sanity check.
429 if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
430 LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
431 << " to " << total_cpu_use_ticks;
432 return TimeDelta();
433 }
434
Ben Chanf05ab402014-08-07 00:54:59 -0700435 uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -0700436 latest_cpu_use_ticks_ = total_cpu_use_ticks;
437 // Use microseconds to avoid significant truncations.
438 return base::TimeDelta::FromMicroseconds(
439 diff * 1000 * 1000 / ticks_per_second_);
440}
441
Darin Petkov1bb904e2010-06-16 15:58:06 -0700442void MetricsDaemon::ProcessUserCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700443 // Counts the active time up to now.
444 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov1bb904e2010-06-16 15:58:06 -0700445
446 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700447 SendAndResetCrashIntervalSample(user_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700448
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800449 any_crashes_daily_count_->Add(1);
450 any_crashes_weekly_count_->Add(1);
451 user_crashes_daily_count_->Add(1);
452 user_crashes_weekly_count_->Add(1);
Darin Petkov1bb904e2010-06-16 15:58:06 -0700453}
454
Darin Petkov38d5cb02010-06-24 12:10:26 -0700455void MetricsDaemon::ProcessKernelCrash() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700456 // Counts the active time up to now.
457 UpdateStats(TimeTicks::Now(), Time::Now());
Darin Petkov38d5cb02010-06-24 12:10:26 -0700458
459 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700460 SendAndResetCrashIntervalSample(kernel_crash_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700461
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800462 any_crashes_daily_count_->Add(1);
463 any_crashes_weekly_count_->Add(1);
464 kernel_crashes_daily_count_->Add(1);
465 kernel_crashes_weekly_count_->Add(1);
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800466
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800467 kernel_crashes_version_count_->Add(1);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700468}
469
Ken Mixterccd84c02010-08-16 19:57:13 -0700470void MetricsDaemon::ProcessUncleanShutdown() {
Daniel Eratc83975a2014-04-04 08:53:44 -0700471 // Counts the active time up to now.
472 UpdateStats(TimeTicks::Now(), Time::Now());
Ken Mixterccd84c02010-08-16 19:57:13 -0700473
474 // Reports the active use time since the last crash and resets it.
Bertrand SIMONNET2d037832015-09-16 17:11:51 -0700475 SendAndResetCrashIntervalSample(unclean_shutdown_interval_);
Ken Mixterccd84c02010-08-16 19:57:13 -0700476
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800477 unclean_shutdowns_daily_count_->Add(1);
478 unclean_shutdowns_weekly_count_->Add(1);
479 any_crashes_daily_count_->Add(1);
480 any_crashes_weekly_count_->Add(1);
Ken Mixterccd84c02010-08-16 19:57:13 -0700481}
482
Luigi Semenzato8accd332011-05-17 16:37:18 -0700483bool MetricsDaemon::CheckSystemCrash(const string& crash_file) {
Darin Petkov38d5cb02010-06-24 12:10:26 -0700484 FilePath crash_detected(crash_file);
Ben Chan2e6543d2014-02-05 23:26:25 -0800485 if (!base::PathExists(crash_detected))
Ken Mixterccd84c02010-08-16 19:57:13 -0700486 return false;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700487
488 // Deletes the crash-detected file so that the daemon doesn't report
489 // another kernel crash in case it's restarted.
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800490 base::DeleteFile(crash_detected, false); // not recursive
Ken Mixterccd84c02010-08-16 19:57:13 -0700491 return true;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700492}
493
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700494void MetricsDaemon::StatsReporterInit() {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800495 DiskStatsReadStats(&read_sectors_, &write_sectors_);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700496 VmStatsReadStats(&vmstats_);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800497 // The first time around just run the long stat, so we don't delay boot.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700498 stats_state_ = kStatsLong;
499 stats_initial_time_ = GetActiveTime();
500 if (stats_initial_time_ < 0) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700501 LOG(WARNING) << "not collecting disk stats";
502 } else {
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700503 ScheduleStatsCallback(kMetricStatsLongInterval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700504 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800505}
506
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700507void MetricsDaemon::ScheduleStatsCallback(int wait) {
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800508 if (testing_) {
509 return;
510 }
Steve Funge86591e2014-12-01 13:38:21 -0800511 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
512 base::Bind(&MetricsDaemon::StatsCallback, base::Unretained(this)),
513 base::TimeDelta::FromSeconds(wait));
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800514}
515
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700516bool MetricsDaemon::DiskStatsReadStats(uint64_t* read_sectors,
517 uint64_t* write_sectors) {
518 CHECK(read_sectors);
519 CHECK(write_sectors);
520 std::string line;
521 if (diskstats_path_.empty()) {
522 return false;
523 }
524
525 if (!base::ReadFileToString(base::FilePath(diskstats_path_), &line)) {
526 PLOG(WARNING) << "Could not read disk stats from " << diskstats_path_;
527 return false;
528 }
529
530 std::vector<std::string> parts = base::SplitString(
531 line, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
532 if (parts.size() != kDiskMetricsStatItemCount) {
533 LOG(ERROR) << "Could not parse disk stat correctly. Expected "
534 << kDiskMetricsStatItemCount << " elements but got "
535 << parts.size();
536 return false;
537 }
538 if (!base::StringToUint64(parts[2], read_sectors)) {
539 LOG(ERROR) << "Couldn't convert read sectors " << parts[2] << " to uint64";
540 return false;
541 }
542 if (!base::StringToUint64(parts[6], write_sectors)) {
543 LOG(ERROR) << "Couldn't convert write sectors " << parts[6] << " to uint64";
544 return false;
545 }
546
547 return true;
548}
549
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700550bool MetricsDaemon::VmStatsParseStats(const char* stats,
551 struct VmstatRecord* record) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700552 CHECK(stats);
553 CHECK(record);
554 base::StringPairs pairs;
555 base::SplitStringIntoKeyValuePairs(stats, ' ', '\n', &pairs);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700556
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700557 for (base::StringPairs::iterator it = pairs.begin(); it != pairs.end(); ++it) {
558 if (it->first == "pgmajfault" &&
559 !base::StringToUint64(it->second, &record->page_faults_)) {
560 return false;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700561 }
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700562 if (it->first == "pswpin" &&
563 !base::StringToUint64(it->second, &record->swap_in_)) {
564 return false;
565 }
566 if (it->first == "pswpout" &&
567 !base::StringToUint64(it->second, &record->swap_out_)) {
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700568 return false;
569 }
570 }
571 return true;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700572}
573
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700574bool MetricsDaemon::VmStatsReadStats(struct VmstatRecord* stats) {
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700575 CHECK(stats);
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700576 string value_string;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700577 if (!base::ReadFileToString(base::FilePath(kVmStatFileName), &value_string)) {
578 LOG(WARNING) << "cannot read " << kVmStatFileName;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700579 return false;
580 }
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700581 return VmStatsParseStats(value_string.c_str(), stats);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800582}
583
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700584bool MetricsDaemon::ReadFreqToInt(const string& sysfs_file_name, int* value) {
Luigi Semenzatod92d18c2013-06-04 13:24:21 -0700585 const FilePath sysfs_path(sysfs_file_name);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700586 string value_string;
Ben Chan2e6543d2014-02-05 23:26:25 -0800587 if (!base::ReadFileToString(sysfs_path, &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700588 LOG(WARNING) << "cannot read " << sysfs_path.value().c_str();
589 return false;
590 }
Ben Chan2e6543d2014-02-05 23:26:25 -0800591 if (!base::RemoveChars(value_string, "\n", &value_string)) {
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700592 LOG(WARNING) << "no newline in " << value_string;
593 // Continue even though the lack of newline is suspicious.
594 }
595 if (!base::StringToInt(value_string, value)) {
596 LOG(WARNING) << "cannot convert " << value_string << " to int";
597 return false;
598 }
599 return true;
600}
601
602void MetricsDaemon::SendCpuThrottleMetrics() {
603 // |max_freq| is 0 only the first time through.
604 static int max_freq = 0;
605 if (max_freq == -1)
606 // Give up, as sysfs did not report max_freq correctly.
607 return;
608 if (max_freq == 0 || testing_) {
609 // One-time initialization of max_freq. (Every time when testing.)
610 if (!ReadFreqToInt(cpuinfo_max_freq_path_, &max_freq)) {
611 max_freq = -1;
612 return;
613 }
614 if (max_freq == 0) {
615 LOG(WARNING) << "sysfs reports 0 max CPU frequency\n";
616 max_freq = -1;
617 return;
618 }
619 if (max_freq % 10000 == 1000) {
620 // Special case: system has turbo mode, and max non-turbo frequency is
621 // max_freq - 1000. This relies on "normal" (non-turbo) frequencies
622 // being multiples of (at least) 10 MHz. Although there is no guarantee
623 // of this, it seems a fairly reasonable assumption. Otherwise we should
624 // read scaling_available_frequencies, sort the frequencies, compare the
625 // two highest ones, and check if they differ by 1000 (kHz) (and that's a
626 // hack too, no telling when it will change).
627 max_freq -= 1000;
628 }
629 }
630 int scaled_freq = 0;
631 if (!ReadFreqToInt(scaling_max_freq_path_, &scaled_freq))
632 return;
633 // Frequencies are in kHz. If scaled_freq > max_freq, turbo is on, but
634 // scaled_freq is not the actual turbo frequency. We indicate this situation
635 // with a 101% value.
636 int percent = scaled_freq > max_freq ? 101 : scaled_freq / (max_freq / 100);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800637 SendLinearSample(kMetricScaledCpuFrequencyName, percent, 101, 102);
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700638}
639
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700640// Collects disk and vm stats alternating over a short and a long interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700641
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700642void MetricsDaemon::StatsCallback() {
Ben Chanf05ab402014-08-07 00:54:59 -0700643 uint64_t read_sectors_now, write_sectors_now;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700644 struct VmstatRecord vmstats_now;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700645 double time_now = GetActiveTime();
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700646 double delta_time = time_now - stats_initial_time_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700647 if (testing_) {
648 // Fake the time when testing.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700649 delta_time = stats_state_ == kStatsShort ?
650 kMetricStatsShortInterval : kMetricStatsLongInterval;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700651 }
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700652 bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
653 &write_sectors_now);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700654 int delta_read = read_sectors_now - read_sectors_;
655 int delta_write = write_sectors_now - write_sectors_;
656 int read_sectors_per_second = delta_read / delta_time;
657 int write_sectors_per_second = delta_write / delta_time;
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700658 bool vmstats_success = VmStatsReadStats(&vmstats_now);
659 uint64_t delta_faults = vmstats_now.page_faults_ - vmstats_.page_faults_;
660 uint64_t delta_swap_in = vmstats_now.swap_in_ - vmstats_.swap_in_;
661 uint64_t delta_swap_out = vmstats_now.swap_out_ - vmstats_.swap_out_;
662 uint64_t page_faults_per_second = delta_faults / delta_time;
663 uint64_t swap_in_per_second = delta_swap_in / delta_time;
664 uint64_t swap_out_per_second = delta_swap_out / delta_time;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800665
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700666 switch (stats_state_) {
667 case kStatsShort:
668 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800669 SendSample(kMetricReadSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700670 read_sectors_per_second,
671 1,
672 kMetricSectorsIOMax,
673 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800674 SendSample(kMetricWriteSectorsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700675 write_sectors_per_second,
676 1,
677 kMetricSectorsIOMax,
678 kMetricSectorsBuckets);
679 }
680 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800681 SendSample(kMetricPageFaultsShortName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700682 page_faults_per_second,
683 1,
684 kMetricPageFaultsMax,
685 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800686 SendSample(kMetricSwapInShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700687 swap_in_per_second,
688 1,
689 kMetricPageFaultsMax,
690 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800691 SendSample(kMetricSwapOutShortName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700692 swap_out_per_second,
693 1,
694 kMetricPageFaultsMax,
695 kMetricPageFaultsBuckets);
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700696 }
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800697 // Schedule long callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700698 stats_state_ = kStatsLong;
699 ScheduleStatsCallback(kMetricStatsLongInterval -
700 kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800701 break;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700702 case kStatsLong:
703 if (diskstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800704 SendSample(kMetricReadSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700705 read_sectors_per_second,
706 1,
707 kMetricSectorsIOMax,
708 kMetricSectorsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800709 SendSample(kMetricWriteSectorsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700710 write_sectors_per_second,
711 1,
712 kMetricSectorsIOMax,
713 kMetricSectorsBuckets);
714 // Reset sector counters.
715 read_sectors_ = read_sectors_now;
716 write_sectors_ = write_sectors_now;
717 }
718 if (vmstats_success) {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800719 SendSample(kMetricPageFaultsLongName,
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700720 page_faults_per_second,
721 1,
722 kMetricPageFaultsMax,
723 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800724 SendSample(kMetricSwapInLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700725 swap_in_per_second,
726 1,
727 kMetricPageFaultsMax,
728 kMetricPageFaultsBuckets);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800729 SendSample(kMetricSwapOutLongName,
Sonny Rao4b8aebb2013-07-31 23:18:31 -0700730 swap_out_per_second,
731 1,
732 kMetricPageFaultsMax,
733 kMetricPageFaultsBuckets);
734
735 vmstats_ = vmstats_now;
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700736 }
Luigi Semenzatofb3a8212013-05-07 16:55:00 -0700737 SendCpuThrottleMetrics();
Luigi Semenzato8accd332011-05-17 16:37:18 -0700738 // Set start time for new cycle.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700739 stats_initial_time_ = time_now;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800740 // Schedule short callback.
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700741 stats_state_ = kStatsShort;
742 ScheduleStatsCallback(kMetricStatsShortInterval);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800743 break;
744 default:
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700745 LOG(FATAL) << "Invalid stats state";
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800746 }
747}
748
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700749void MetricsDaemon::ScheduleMeminfoCallback(int wait) {
750 if (testing_) {
751 return;
752 }
Steve Funge86591e2014-12-01 13:38:21 -0800753 base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
754 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
755 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800756 waitDelta),
Steve Funge86591e2014-12-01 13:38:21 -0800757 waitDelta);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700758}
759
Steve Funge86591e2014-12-01 13:38:21 -0800760void MetricsDaemon::MeminfoCallback(base::TimeDelta wait) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700761 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700762 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800763 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700764 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
Steve Funge86591e2014-12-01 13:38:21 -0800765 return;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700766 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700767 // Make both calls even if the first one fails.
Bertrand SIMONNETebbe35c2015-09-08 10:13:35 -0700768 if (ProcessMeminfo(meminfo_raw)) {
Steve Funge86591e2014-12-01 13:38:21 -0800769 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
770 base::Bind(&MetricsDaemon::MeminfoCallback, base::Unretained(this),
Steve Fung8ab89c52015-01-05 13:48:30 -0800771 wait),
Steve Funge86591e2014-12-01 13:38:21 -0800772 wait);
773 }
Luigi Semenzato96360192014-06-04 10:53:35 -0700774}
775
776// static
777bool MetricsDaemon::ReadFileToUint64(const base::FilePath& path,
Ben Chanf05ab402014-08-07 00:54:59 -0700778 uint64_t* value) {
Luigi Semenzato96360192014-06-04 10:53:35 -0700779 std::string content;
780 if (!base::ReadFileToString(path, &content)) {
781 PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
782 return false;
783 }
Luigi Semenzato4a6c9422014-06-30 18:12:28 -0700784 // Remove final newline.
785 base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
Luigi Semenzato96360192014-06-04 10:53:35 -0700786 if (!base::StringToUint64(content, value)) {
787 LOG(WARNING) << "invalid integer: " << content;
788 return false;
789 }
790 return true;
791}
792
793bool MetricsDaemon::ReportZram(const base::FilePath& zram_dir) {
794 // Data sizes are in bytes. |zero_pages| is in number of pages.
Ben Chanf05ab402014-08-07 00:54:59 -0700795 uint64_t compr_data_size, orig_data_size, zero_pages;
Luigi Semenzato96360192014-06-04 10:53:35 -0700796 const size_t page_size = 4096;
797
798 if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
799 &compr_data_size) ||
800 !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
801 !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
802 return false;
803 }
804
805 // |orig_data_size| does not include zero-filled pages.
806 orig_data_size += zero_pages * page_size;
807
808 const int compr_data_size_mb = compr_data_size >> 20;
809 const int savings_mb = (orig_data_size - compr_data_size) >> 20;
810 const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
811
812 // Report compressed size in megabytes. 100 MB or less has little impact.
813 SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
814 SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
815 // The compression ratio is multiplied by 100 for better resolution. The
816 // ratios of interest are between 1 and 6 (100% and 600% as reported). We
817 // don't want samples when very little memory is being compressed.
818 if (compr_data_size_mb >= 1) {
819 SendSample("Platform.ZramCompressionRatioPercent",
820 orig_data_size * 100 / compr_data_size, 100, 600, 50);
821 }
822 // The values of interest for zero_pages are between 1MB and 1GB. The units
823 // are number of pages.
824 SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
825 SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
826
827 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700828}
829
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700830bool MetricsDaemon::ProcessMeminfo(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700831 static const MeminfoRecord fields_array[] = {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700832 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
833 { "MemFree", "MemFree" },
834 { "Buffers", "Buffers" },
835 { "Cached", "Cached" },
836 // { "SwapCached", "SwapCached" },
837 { "Active", "Active" },
838 { "Inactive", "Inactive" },
839 { "ActiveAnon", "Active(anon)" },
840 { "InactiveAnon", "Inactive(anon)" },
841 { "ActiveFile" , "Active(file)" },
842 { "InactiveFile", "Inactive(file)" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800843 { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700844 // { "Mlocked", "Mlocked" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800845 { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
846 { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700847 // { "Dirty", "Dirty" },
848 // { "Writeback", "Writeback" },
849 { "AnonPages", "AnonPages" },
850 { "Mapped", "Mapped" },
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800851 { "Shmem", "Shmem", kMeminfoOp_HistLog },
852 { "Slab", "Slab", kMeminfoOp_HistLog },
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700853 // { "SReclaimable", "SReclaimable" },
854 // { "SUnreclaim", "SUnreclaim" },
855 };
Luigi Semenzato8accd332011-05-17 16:37:18 -0700856 vector<MeminfoRecord> fields(fields_array,
857 fields_array + arraysize(fields_array));
858 if (!FillMeminfo(meminfo_raw, &fields)) {
859 return false;
860 }
861 int total_memory = fields[0].value;
862 if (total_memory == 0) {
863 // this "cannot happen"
864 LOG(WARNING) << "borked meminfo parser";
865 return false;
866 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800867 int swap_total = 0;
868 int swap_free = 0;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700869 // Send all fields retrieved, except total memory.
870 for (unsigned int i = 1; i < fields.size(); i++) {
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800871 string metrics_name = base::StringPrintf("Platform.Meminfo%s",
872 fields[i].name);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800873 int percent;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800874 switch (fields[i].op) {
875 case kMeminfoOp_HistPercent:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800876 // report value as percent of total memory
877 percent = fields[i].value * 100 / total_memory;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800878 SendLinearSample(metrics_name, percent, 100, 101);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800879 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800880 case kMeminfoOp_HistLog:
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800881 // report value in kbytes, log scale, 4Gb max
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800882 SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800883 break;
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800884 case kMeminfoOp_SwapTotal:
885 swap_total = fields[i].value;
886 case kMeminfoOp_SwapFree:
887 swap_free = fields[i].value;
Luigi Semenzato3ccca062013-02-04 19:50:45 -0800888 break;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700889 }
890 }
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800891 if (swap_total > 0) {
892 int swap_used = swap_total - swap_free;
893 int swap_used_percent = swap_used * 100 / swap_total;
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800894 SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
895 SendLinearSample("Platform.MeminfoSwapUsedPercent", swap_used_percent,
Luigi Semenzato942cbab2013-02-12 13:17:07 -0800896 100, 101);
897 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700898 return true;
899}
900
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700901bool MetricsDaemon::FillMeminfo(const string& meminfo_raw,
902 vector<MeminfoRecord>* fields) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700903 vector<string> lines;
904 unsigned int nlines = Tokenize(meminfo_raw, "\n", &lines);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700905
906 // Scan meminfo output and collect field values. Each field name has to
907 // match a meminfo entry (case insensitive) after removing non-alpha
908 // characters from the entry.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700909 unsigned int ifield = 0;
910 for (unsigned int iline = 0;
911 iline < nlines && ifield < fields->size();
912 iline++) {
913 vector<string> tokens;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700914 Tokenize(lines[iline], ": ", &tokens);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700915 if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
916 // Name matches. Parse value and save.
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700917 if (!base::StringToInt(tokens[1], &(*fields)[ifield].value)) {
918 LOG(WARNING) << "Cound not convert " << tokens[1] << " to int";
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700919 return false;
920 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700921 ifield++;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700922 }
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700923 }
Luigi Semenzato8accd332011-05-17 16:37:18 -0700924 if (ifield < fields->size()) {
925 // End of input reached while scanning.
926 LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
927 << " and following";
928 return false;
929 }
930 return true;
931}
932
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800933void MetricsDaemon::ScheduleMemuseCallback(double interval) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700934 if (testing_) {
935 return;
936 }
Steve Funge86591e2014-12-01 13:38:21 -0800937 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
938 base::Bind(&MetricsDaemon::MemuseCallback, base::Unretained(this)),
939 base::TimeDelta::FromSeconds(interval));
Luigi Semenzato8accd332011-05-17 16:37:18 -0700940}
941
942void MetricsDaemon::MemuseCallback() {
943 // Since we only care about active time (i.e. uptime minus sleep time) but
944 // the callbacks are driven by real time (uptime), we check if we should
945 // reschedule this callback due to intervening sleep periods.
946 double now = GetActiveTime();
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800947 // Avoid intervals of less than one second.
948 double remaining_time = ceil(memuse_final_time_ - now);
949 if (remaining_time > 0) {
950 ScheduleMemuseCallback(remaining_time);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700951 } else {
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800952 // Report stats and advance the measurement interval unless there are
953 // errors or we've completed the last interval.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700954 if (MemuseCallbackWork() &&
Luigi Semenzato0d9a9c92013-12-05 15:55:12 -0800955 memuse_interval_index_ < arraysize(kMemuseIntervals)) {
956 double interval = kMemuseIntervals[memuse_interval_index_++];
957 memuse_final_time_ = now + interval;
958 ScheduleMemuseCallback(interval);
Luigi Semenzato8accd332011-05-17 16:37:18 -0700959 }
960 }
961}
962
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700963bool MetricsDaemon::MemuseCallbackWork() {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700964 string meminfo_raw;
Bertrand SIMONNET675a10c2015-08-25 14:11:43 -0700965 const FilePath meminfo_path(kMeminfoFileName);
Ben Chan2e6543d2014-02-05 23:26:25 -0800966 if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700967 LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
968 return false;
969 }
970 return ProcessMemuse(meminfo_raw);
971}
972
Luigi Semenzato5bd764f2011-10-14 12:03:35 -0700973bool MetricsDaemon::ProcessMemuse(const string& meminfo_raw) {
Luigi Semenzato8accd332011-05-17 16:37:18 -0700974 static const MeminfoRecord fields_array[] = {
975 { "MemTotal", "MemTotal" }, // SPECIAL CASE: total system memory
976 { "ActiveAnon", "Active(anon)" },
977 { "InactiveAnon", "Inactive(anon)" },
978 };
979 vector<MeminfoRecord> fields(fields_array,
980 fields_array + arraysize(fields_array));
981 if (!FillMeminfo(meminfo_raw, &fields)) {
982 return false;
983 }
984 int total = fields[0].value;
985 int active_anon = fields[1].value;
986 int inactive_anon = fields[2].value;
987 if (total == 0) {
988 // this "cannot happen"
989 LOG(WARNING) << "borked meminfo parser";
990 return false;
991 }
Luigi Semenzato859b3f02014-02-05 15:33:19 -0800992 string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
993 memuse_interval_index_);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800994 SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
Luigi Semenzato8accd332011-05-17 16:37:18 -0700995 100, 101);
996 return true;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700997}
998
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -0800999void MetricsDaemon::SendSample(const string& name, int sample,
Darin Petkov11b8eb32010-05-18 11:00:59 -07001000 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -07001001 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -07001002}
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001003
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001004void MetricsDaemon::SendKernelCrashesCumulativeCountStats() {
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001005 // Report the number of crashes for this OS version, but don't clear the
1006 // counter. It is cleared elsewhere on version change.
Ben Chanf05ab402014-08-07 00:54:59 -07001007 int64_t crashes_count = kernel_crashes_version_count_->Get();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001008 SendSample(kernel_crashes_version_count_->Name(),
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001009 crashes_count,
1010 1, // value of first bucket
1011 500, // value of last bucket
1012 100); // number of buckets
1013
1014
Ben Chanf05ab402014-08-07 00:54:59 -07001015 int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001016 SendSample(version_cumulative_cpu_use_->Name(),
1017 cpu_use_ms / 1000, // stat is in seconds
1018 1, // device may be used very little...
1019 8 * 1000 * 1000, // ... or a lot (a little over 90 days)
1020 100);
1021
1022 // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
1023 // can be zero. Avoid division by zero.
1024 if (cpu_use_ms > 0) {
1025 // Send the crash frequency since update in number of crashes per CPU year.
1026 SendSample("Logging.KernelCrashesPerCpuYear",
1027 crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
1028 1,
1029 1000 * 1000, // about one crash every 30s of CPU time
1030 100);
1031 }
1032
Ben Chanf05ab402014-08-07 00:54:59 -07001033 int64_t active_use_seconds = version_cumulative_active_use_->Get();
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001034 if (active_use_seconds > 0) {
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001035 SendSample(version_cumulative_active_use_->Name(),
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001036 active_use_seconds,
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001037 1, // device may be used very little...
1038 8 * 1000 * 1000, // ... or a lot (about 90 days)
1039 100);
Luigi Semenzatoba0c65d2014-03-17 12:28:38 -07001040 // Same as above, but per year of active time.
1041 SendSample("Logging.KernelCrashesPerActiveYear",
1042 crashes_count * kSecondsPerDay * 365 / active_use_seconds,
1043 1,
1044 1000 * 1000, // about one crash every 30s of active time
1045 100);
1046 }
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001047}
1048
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001049void MetricsDaemon::SendAndResetDailyUseSample(
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001050 const scoped_ptr<PersistentInteger>& use) {
1051 SendSample(use->Name(),
1052 use->GetAndClear(),
1053 1, // value of first bucket
1054 kSecondsPerDay, // value of last bucket
1055 50); // number of buckets
1056}
1057
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001058void MetricsDaemon::SendAndResetCrashIntervalSample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001059 const scoped_ptr<PersistentInteger>& interval) {
1060 SendSample(interval->Name(),
1061 interval->GetAndClear(),
1062 1, // value of first bucket
1063 4 * kSecondsPerWeek, // value of last bucket
1064 50); // number of buckets
1065}
1066
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001067void MetricsDaemon::SendAndResetCrashFrequencySample(
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001068 const scoped_ptr<PersistentInteger>& frequency) {
1069 SendSample(frequency->Name(),
1070 frequency->GetAndClear(),
1071 1, // value of first bucket
1072 100, // value of last bucket
1073 50); // number of buckets
1074}
1075
1076void MetricsDaemon::SendLinearSample(const string& name, int sample,
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001077 int max, int nbuckets) {
Luigi Semenzato29c7ef92011-04-12 14:12:35 -07001078 // TODO(semenzato): add a proper linear histogram to the Chrome external
1079 // metrics API.
1080 LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
1081 metrics_lib_->SendEnumToUMA(name, sample, max);
1082}
Daniel Eratc83975a2014-04-04 08:53:44 -07001083
1084void MetricsDaemon::UpdateStats(TimeTicks now_ticks,
1085 Time now_wall_time) {
1086 const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001087 daily_active_use_->Add(elapsed_seconds);
1088 version_cumulative_active_use_->Add(elapsed_seconds);
Daniel Eratc83975a2014-04-04 08:53:44 -07001089 user_crash_interval_->Add(elapsed_seconds);
1090 kernel_crash_interval_->Add(elapsed_seconds);
1091 version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
1092 last_update_stats_time_ = now_ticks;
1093
1094 const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
1095 const int day = since_epoch.InDays();
1096 const int week = day / 7;
1097
1098 if (daily_cycle_->Get() != day) {
1099 daily_cycle_->Set(day);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001100 SendAndResetDailyUseSample(daily_active_use_);
1101 SendAndResetCrashFrequencySample(any_crashes_daily_count_);
1102 SendAndResetCrashFrequencySample(user_crashes_daily_count_);
1103 SendAndResetCrashFrequencySample(kernel_crashes_daily_count_);
1104 SendAndResetCrashFrequencySample(unclean_shutdowns_daily_count_);
Luigi Semenzatoe5883fa2014-04-18 17:00:35 -07001105 SendKernelCrashesCumulativeCountStats();
Daniel Eratc83975a2014-04-04 08:53:44 -07001106 }
1107
1108 if (weekly_cycle_->Get() != week) {
1109 weekly_cycle_->Set(week);
Bertrand SIMONNET2d037832015-09-16 17:11:51 -07001110 SendAndResetCrashFrequencySample(any_crashes_weekly_count_);
1111 SendAndResetCrashFrequencySample(user_crashes_weekly_count_);
1112 SendAndResetCrashFrequencySample(kernel_crashes_weekly_count_);
1113 SendAndResetCrashFrequencySample(unclean_shutdowns_weekly_count_);
Daniel Eratc83975a2014-04-04 08:53:44 -07001114 }
1115}
1116
Steve Funge86591e2014-12-01 13:38:21 -08001117void MetricsDaemon::HandleUpdateStatsTimeout() {
1118 UpdateStats(TimeTicks::Now(), Time::Now());
1119 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
1120 base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
1121 base::Unretained(this)),
1122 base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
Daniel Eratc83975a2014-04-04 08:53:44 -07001123}