Don't schedule more invokeFunctors than necessary.
[chromium-blink-merge.git] / components / metrics / metrics_log.cc
blobfdfe3056c796e3efae1cb99dde94714b51cb7ae8
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/metrics/metrics_log.h"
7 #include <algorithm>
8 #include <string>
9 #include <vector>
11 #include "base/base64.h"
12 #include "base/basictypes.h"
13 #include "base/build_time.h"
14 #include "base/cpu.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/metrics/histogram.h"
17 #include "base/metrics/histogram_samples.h"
18 #include "base/prefs/pref_registry_simple.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/sha1.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/sys_info.h"
25 #include "base/time/time.h"
26 #include "components/metrics/histogram_encoder.h"
27 #include "components/metrics/metrics_hashes.h"
28 #include "components/metrics/metrics_pref_names.h"
29 #include "components/metrics/metrics_provider.h"
30 #include "components/metrics/metrics_service_client.h"
31 #include "components/metrics/proto/histogram_event.pb.h"
32 #include "components/metrics/proto/system_profile.pb.h"
33 #include "components/metrics/proto/user_action_event.pb.h"
34 #include "components/variations/active_field_trials.h"
36 #if defined(OS_ANDROID)
37 #include "base/android/build_info.h"
38 #endif
40 #if defined(OS_WIN)
41 #include "base/win/metro.h"
43 // http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
44 extern "C" IMAGE_DOS_HEADER __ImageBase;
45 #endif
47 using base::SampleCountIterator;
48 typedef variations::ActiveGroupId ActiveGroupId;
50 namespace metrics {
52 namespace {
54 // Any id less than 16 bytes is considered to be a testing id.
55 bool IsTestingID(const std::string& id) {
56 return id.size() < 16;
59 // Returns the date at which the current metrics client ID was created as
60 // a string containing seconds since the epoch, or "0" if none was found.
61 std::string GetMetricsEnabledDate(PrefService* pref) {
62 if (!pref) {
63 NOTREACHED();
64 return "0";
67 return pref->GetString(prefs::kMetricsReportingEnabledTimestamp);
70 // Computes a SHA-1 hash of |data| and returns it as a hex string.
71 std::string ComputeSHA1(const std::string& data) {
72 const std::string sha1 = base::SHA1HashString(data);
73 return base::HexEncode(sha1.data(), sha1.size());
76 void WriteFieldTrials(const std::vector<ActiveGroupId>& field_trial_ids,
77 SystemProfileProto* system_profile) {
78 for (std::vector<ActiveGroupId>::const_iterator it =
79 field_trial_ids.begin(); it != field_trial_ids.end(); ++it) {
80 SystemProfileProto::FieldTrial* field_trial =
81 system_profile->add_field_trial();
82 field_trial->set_name_id(it->name);
83 field_trial->set_group_id(it->group);
87 // Round a timestamp measured in seconds since epoch to one with a granularity
88 // of an hour. This can be used before uploaded potentially sensitive
89 // timestamps.
90 int64 RoundSecondsToHour(int64 time_in_seconds) {
91 return 3600 * (time_in_seconds / 3600);
94 } // namespace
96 MetricsLog::MetricsLog(const std::string& client_id,
97 int session_id,
98 LogType log_type,
99 MetricsServiceClient* client,
100 PrefService* local_state)
101 : closed_(false),
102 log_type_(log_type),
103 client_(client),
104 creation_time_(base::TimeTicks::Now()),
105 local_state_(local_state) {
106 if (IsTestingID(client_id))
107 uma_proto_.set_client_id(0);
108 else
109 uma_proto_.set_client_id(Hash(client_id));
111 uma_proto_.set_session_id(session_id);
113 const int32 product = client_->GetProduct();
114 // Only set the product if it differs from the default value.
115 if (product != uma_proto_.product())
116 uma_proto_.set_product(product);
118 SystemProfileProto* system_profile = uma_proto_.mutable_system_profile();
119 system_profile->set_build_timestamp(GetBuildTime());
120 system_profile->set_app_version(client_->GetVersionString());
121 system_profile->set_channel(client_->GetChannel());
124 MetricsLog::~MetricsLog() {
127 // static
128 void MetricsLog::RegisterPrefs(PrefRegistrySimple* registry) {
129 registry->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
130 registry->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
131 registry->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount, 0);
132 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail, 0);
133 registry->RegisterIntegerPref(
134 prefs::kStabilityBreakpadRegistrationSuccess, 0);
135 registry->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
136 registry->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
137 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfile,
138 std::string());
139 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfileHash,
140 std::string());
143 // static
144 uint64 MetricsLog::Hash(const std::string& value) {
145 uint64 hash = HashMetricName(value);
147 // The following log is VERY helpful when folks add some named histogram into
148 // the code, but forgot to update the descriptive list of histograms. When
149 // that happens, all we get to see (server side) is a hash of the histogram
150 // name. We can then use this logging to find out what histogram name was
151 // being hashed to a given MD5 value by just running the version of Chromium
152 // in question with --enable-logging.
153 DVLOG(1) << "Metrics: Hash numeric [" << value << "]=[" << hash << "]";
155 return hash;
158 // static
159 int64 MetricsLog::GetBuildTime() {
160 static int64 integral_build_time = 0;
161 if (!integral_build_time)
162 integral_build_time = static_cast<int64>(base::GetBuildTime().ToTimeT());
163 return integral_build_time;
166 // static
167 int64 MetricsLog::GetCurrentTime() {
168 return (base::TimeTicks::Now() - base::TimeTicks()).InSeconds();
171 void MetricsLog::RecordUserAction(const std::string& key) {
172 DCHECK(!closed_);
174 UserActionEventProto* user_action = uma_proto_.add_user_action_event();
175 user_action->set_name_hash(Hash(key));
176 user_action->set_time(GetCurrentTime());
179 void MetricsLog::RecordHistogramDelta(const std::string& histogram_name,
180 const base::HistogramSamples& snapshot) {
181 DCHECK(!closed_);
182 EncodeHistogramDelta(histogram_name, snapshot, &uma_proto_);
185 void MetricsLog::RecordStabilityMetrics(
186 const std::vector<MetricsProvider*>& metrics_providers,
187 base::TimeDelta incremental_uptime,
188 base::TimeDelta uptime) {
189 DCHECK(!closed_);
190 DCHECK(HasEnvironment());
191 DCHECK(!HasStabilityMetrics());
193 PrefService* pref = local_state_;
194 DCHECK(pref);
196 // Get stability attributes out of Local State, zeroing out stored values.
197 // NOTE: This could lead to some data loss if this report isn't successfully
198 // sent, but that's true for all the metrics.
200 WriteRequiredStabilityAttributes(pref);
202 // Record recent delta for critical stability metrics. We can't wait for a
203 // restart to gather these, as that delay biases our observation away from
204 // users that run happily for a looooong time. We send increments with each
205 // uma log upload, just as we send histogram data.
206 WriteRealtimeStabilityAttributes(pref, incremental_uptime, uptime);
208 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
209 for (size_t i = 0; i < metrics_providers.size(); ++i)
210 metrics_providers[i]->ProvideStabilityMetrics(system_profile);
212 // Omit some stats unless this is the initial stability log.
213 if (log_type() != INITIAL_STABILITY_LOG)
214 return;
216 int incomplete_shutdown_count =
217 pref->GetInteger(prefs::kStabilityIncompleteSessionEndCount);
218 pref->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
219 int breakpad_registration_success_count =
220 pref->GetInteger(prefs::kStabilityBreakpadRegistrationSuccess);
221 pref->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
222 int breakpad_registration_failure_count =
223 pref->GetInteger(prefs::kStabilityBreakpadRegistrationFail);
224 pref->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
225 int debugger_present_count =
226 pref->GetInteger(prefs::kStabilityDebuggerPresent);
227 pref->SetInteger(prefs::kStabilityDebuggerPresent, 0);
228 int debugger_not_present_count =
229 pref->GetInteger(prefs::kStabilityDebuggerNotPresent);
230 pref->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
232 // TODO(jar): The following are all optional, so we *could* optimize them for
233 // values of zero (and not include them).
234 SystemProfileProto::Stability* stability =
235 system_profile->mutable_stability();
236 stability->set_incomplete_shutdown_count(incomplete_shutdown_count);
237 stability->set_breakpad_registration_success_count(
238 breakpad_registration_success_count);
239 stability->set_breakpad_registration_failure_count(
240 breakpad_registration_failure_count);
241 stability->set_debugger_present_count(debugger_present_count);
242 stability->set_debugger_not_present_count(debugger_not_present_count);
245 void MetricsLog::RecordGeneralMetrics(
246 const std::vector<MetricsProvider*>& metrics_providers) {
247 for (size_t i = 0; i < metrics_providers.size(); ++i)
248 metrics_providers[i]->ProvideGeneralMetrics(uma_proto());
251 void MetricsLog::GetFieldTrialIds(
252 std::vector<ActiveGroupId>* field_trial_ids) const {
253 variations::GetFieldTrialActiveGroupIds(field_trial_ids);
256 bool MetricsLog::HasEnvironment() const {
257 return uma_proto()->system_profile().has_uma_enabled_date();
260 bool MetricsLog::HasStabilityMetrics() const {
261 return uma_proto()->system_profile().stability().has_launch_count();
264 // The server refuses data that doesn't have certain values. crashcount and
265 // launchcount are currently "required" in the "stability" group.
266 // TODO(isherman): Stop writing these attributes specially once the migration to
267 // protobufs is complete.
268 void MetricsLog::WriteRequiredStabilityAttributes(PrefService* pref) {
269 int launch_count = pref->GetInteger(prefs::kStabilityLaunchCount);
270 pref->SetInteger(prefs::kStabilityLaunchCount, 0);
271 int crash_count = pref->GetInteger(prefs::kStabilityCrashCount);
272 pref->SetInteger(prefs::kStabilityCrashCount, 0);
274 SystemProfileProto::Stability* stability =
275 uma_proto()->mutable_system_profile()->mutable_stability();
276 stability->set_launch_count(launch_count);
277 stability->set_crash_count(crash_count);
280 void MetricsLog::WriteRealtimeStabilityAttributes(
281 PrefService* pref,
282 base::TimeDelta incremental_uptime,
283 base::TimeDelta uptime) {
284 // Update the stats which are critical for real-time stability monitoring.
285 // Since these are "optional," only list ones that are non-zero, as the counts
286 // are aggregated (summed) server side.
288 SystemProfileProto::Stability* stability =
289 uma_proto()->mutable_system_profile()->mutable_stability();
291 const uint64 incremental_uptime_sec = incremental_uptime.InSeconds();
292 if (incremental_uptime_sec)
293 stability->set_incremental_uptime_sec(incremental_uptime_sec);
294 const uint64 uptime_sec = uptime.InSeconds();
295 if (uptime_sec)
296 stability->set_uptime_sec(uptime_sec);
299 void MetricsLog::RecordEnvironment(
300 const std::vector<MetricsProvider*>& metrics_providers,
301 const std::vector<variations::ActiveGroupId>& synthetic_trials,
302 int64 install_date) {
303 DCHECK(!HasEnvironment());
305 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
307 std::string brand_code;
308 if (client_->GetBrand(&brand_code))
309 system_profile->set_brand_code(brand_code);
311 int enabled_date;
312 bool success =
313 base::StringToInt(GetMetricsEnabledDate(local_state_), &enabled_date);
314 DCHECK(success);
316 // Reduce granularity of the enabled_date field to nearest hour.
317 system_profile->set_uma_enabled_date(RoundSecondsToHour(enabled_date));
319 // Reduce granularity of the install_date field to nearest hour.
320 system_profile->set_install_date(RoundSecondsToHour(install_date));
322 system_profile->set_application_locale(client_->GetApplicationLocale());
324 SystemProfileProto::Hardware* hardware = system_profile->mutable_hardware();
326 // HardwareModelName() will return an empty string on platforms where it's
327 // not implemented or if an error occured.
328 hardware->set_hardware_class(base::SysInfo::HardwareModelName());
330 hardware->set_cpu_architecture(base::SysInfo::OperatingSystemArchitecture());
331 hardware->set_system_ram_mb(base::SysInfo::AmountOfPhysicalMemoryMB());
332 #if defined(OS_WIN)
333 hardware->set_dll_base(reinterpret_cast<uint64>(&__ImageBase));
334 #endif
336 SystemProfileProto::OS* os = system_profile->mutable_os();
337 std::string os_name = base::SysInfo::OperatingSystemName();
338 #if defined(OS_WIN)
339 // TODO(mad): This only checks whether the main process is a Metro process at
340 // upload time; not whether the collected metrics were all gathered from
341 // Metro. This is ok as an approximation for now, since users will rarely be
342 // switching from Metro to Desktop mode; but we should re-evaluate whether we
343 // can distinguish metrics more cleanly in the future: http://crbug.com/140568
344 if (base::win::IsMetroProcess())
345 os_name += " (Metro)";
346 #endif
347 os->set_name(os_name);
348 os->set_version(base::SysInfo::OperatingSystemVersion());
349 #if defined(OS_ANDROID)
350 os->set_fingerprint(
351 base::android::BuildInfo::GetInstance()->android_build_fp());
352 #endif
354 base::CPU cpu_info;
355 SystemProfileProto::Hardware::CPU* cpu = hardware->mutable_cpu();
356 cpu->set_vendor_name(cpu_info.vendor_name());
357 cpu->set_signature(cpu_info.signature());
359 std::vector<ActiveGroupId> field_trial_ids;
360 GetFieldTrialIds(&field_trial_ids);
361 WriteFieldTrials(field_trial_ids, system_profile);
362 WriteFieldTrials(synthetic_trials, system_profile);
364 for (size_t i = 0; i < metrics_providers.size(); ++i)
365 metrics_providers[i]->ProvideSystemProfileMetrics(system_profile);
367 std::string serialied_system_profile;
368 std::string base64_system_profile;
369 if (system_profile->SerializeToString(&serialied_system_profile)) {
370 base::Base64Encode(serialied_system_profile, &base64_system_profile);
371 PrefService* local_state = local_state_;
372 local_state->SetString(prefs::kStabilitySavedSystemProfile,
373 base64_system_profile);
374 local_state->SetString(prefs::kStabilitySavedSystemProfileHash,
375 ComputeSHA1(serialied_system_profile));
379 bool MetricsLog::LoadSavedEnvironmentFromPrefs() {
380 PrefService* local_state = local_state_;
381 const std::string base64_system_profile =
382 local_state->GetString(prefs::kStabilitySavedSystemProfile);
383 if (base64_system_profile.empty())
384 return false;
386 const std::string system_profile_hash =
387 local_state->GetString(prefs::kStabilitySavedSystemProfileHash);
388 local_state->ClearPref(prefs::kStabilitySavedSystemProfile);
389 local_state->ClearPref(prefs::kStabilitySavedSystemProfileHash);
391 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
392 std::string serialied_system_profile;
393 return base::Base64Decode(base64_system_profile, &serialied_system_profile) &&
394 ComputeSHA1(serialied_system_profile) == system_profile_hash &&
395 system_profile->ParseFromString(serialied_system_profile);
398 void MetricsLog::CloseLog() {
399 DCHECK(!closed_);
400 closed_ = true;
403 void MetricsLog::GetEncodedLog(std::string* encoded_log) {
404 DCHECK(closed_);
405 uma_proto_.SerializeToString(encoded_log);
408 } // namespace metrics