Temporarily re-enabling SizeAfterPrefChange test with traces (this time for Linux...
[chromium-blink-merge.git] / chrome / browser / metrics / metrics_log.cc
blob2303ccaf7f5490dd31a9f67b562e49899dff697f
1 // Copyright (c) 2012 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 "chrome/browser/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/bind.h"
14 #include "base/cpu.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/prefs/pref_registry_simple.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/sha1.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/sys_info.h"
23 #include "base/time/time.h"
24 #include "chrome/common/pref_names.h"
25 #include "components/metrics/metrics_provider.h"
26 #include "components/metrics/metrics_service_client.h"
27 #include "components/metrics/proto/system_profile.pb.h"
28 #include "components/variations/active_field_trials.h"
30 #if defined(OS_ANDROID)
31 #include "base/android/build_info.h"
32 #endif
34 #if defined(OS_WIN)
35 #include "base/win/metro.h"
37 // http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
38 extern "C" IMAGE_DOS_HEADER __ImageBase;
39 #endif
41 using metrics::MetricsLogBase;
42 using metrics::ProfilerEventProto;
43 using metrics::SystemProfileProto;
44 typedef variations::ActiveGroupId ActiveGroupId;
46 namespace {
48 // Returns the date at which the current metrics client ID was created as
49 // a string containing seconds since the epoch, or "0" if none was found.
50 std::string GetMetricsEnabledDate(PrefService* pref) {
51 if (!pref) {
52 NOTREACHED();
53 return "0";
56 return pref->GetString(prefs::kMetricsReportingEnabledTimestamp);
59 // Computes a SHA-1 hash of |data| and returns it as a hex string.
60 std::string ComputeSHA1(const std::string& data) {
61 const std::string sha1 = base::SHA1HashString(data);
62 return base::HexEncode(sha1.data(), sha1.size());
65 void WriteFieldTrials(const std::vector<ActiveGroupId>& field_trial_ids,
66 SystemProfileProto* system_profile) {
67 for (std::vector<ActiveGroupId>::const_iterator it =
68 field_trial_ids.begin(); it != field_trial_ids.end(); ++it) {
69 SystemProfileProto::FieldTrial* field_trial =
70 system_profile->add_field_trial();
71 field_trial->set_name_id(it->name);
72 field_trial->set_group_id(it->group);
76 // Round a timestamp measured in seconds since epoch to one with a granularity
77 // of an hour. This can be used before uploaded potentially sensitive
78 // timestamps.
79 int64 RoundSecondsToHour(int64 time_in_seconds) {
80 return 3600 * (time_in_seconds / 3600);
83 } // namespace
85 MetricsLog::MetricsLog(const std::string& client_id,
86 int session_id,
87 LogType log_type,
88 metrics::MetricsServiceClient* client,
89 PrefService* local_state)
90 : MetricsLogBase(client_id,
91 session_id,
92 log_type,
93 client->GetVersionString()),
94 client_(client),
95 creation_time_(base::TimeTicks::Now()),
96 local_state_(local_state) {
97 uma_proto()->mutable_system_profile()->set_channel(client_->GetChannel());
100 MetricsLog::~MetricsLog() {}
102 void MetricsLog::RecordStabilityMetrics(
103 const std::vector<metrics::MetricsProvider*>& metrics_providers,
104 base::TimeDelta incremental_uptime,
105 base::TimeDelta uptime) {
106 DCHECK(!locked());
107 DCHECK(HasEnvironment());
108 DCHECK(!HasStabilityMetrics());
110 PrefService* pref = local_state_;
111 DCHECK(pref);
113 // Get stability attributes out of Local State, zeroing out stored values.
114 // NOTE: This could lead to some data loss if this report isn't successfully
115 // sent, but that's true for all the metrics.
117 WriteRequiredStabilityAttributes(pref);
119 // Record recent delta for critical stability metrics. We can't wait for a
120 // restart to gather these, as that delay biases our observation away from
121 // users that run happily for a looooong time. We send increments with each
122 // uma log upload, just as we send histogram data.
123 WriteRealtimeStabilityAttributes(pref, incremental_uptime, uptime);
125 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
126 for (size_t i = 0; i < metrics_providers.size(); ++i)
127 metrics_providers[i]->ProvideStabilityMetrics(system_profile);
129 // Omit some stats unless this is the initial stability log.
130 if (log_type() != INITIAL_STABILITY_LOG)
131 return;
133 int incomplete_shutdown_count =
134 pref->GetInteger(prefs::kStabilityIncompleteSessionEndCount);
135 pref->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
136 int breakpad_registration_success_count =
137 pref->GetInteger(prefs::kStabilityBreakpadRegistrationSuccess);
138 pref->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
139 int breakpad_registration_failure_count =
140 pref->GetInteger(prefs::kStabilityBreakpadRegistrationFail);
141 pref->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
142 int debugger_present_count =
143 pref->GetInteger(prefs::kStabilityDebuggerPresent);
144 pref->SetInteger(prefs::kStabilityDebuggerPresent, 0);
145 int debugger_not_present_count =
146 pref->GetInteger(prefs::kStabilityDebuggerNotPresent);
147 pref->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
149 // TODO(jar): The following are all optional, so we *could* optimize them for
150 // values of zero (and not include them).
151 SystemProfileProto::Stability* stability =
152 system_profile->mutable_stability();
153 stability->set_incomplete_shutdown_count(incomplete_shutdown_count);
154 stability->set_breakpad_registration_success_count(
155 breakpad_registration_success_count);
156 stability->set_breakpad_registration_failure_count(
157 breakpad_registration_failure_count);
158 stability->set_debugger_present_count(debugger_present_count);
159 stability->set_debugger_not_present_count(debugger_not_present_count);
162 void MetricsLog::RecordGeneralMetrics(
163 const std::vector<metrics::MetricsProvider*>& metrics_providers) {
164 for (size_t i = 0; i < metrics_providers.size(); ++i)
165 metrics_providers[i]->ProvideGeneralMetrics(uma_proto());
168 void MetricsLog::GetFieldTrialIds(
169 std::vector<ActiveGroupId>* field_trial_ids) const {
170 variations::GetFieldTrialActiveGroupIds(field_trial_ids);
173 bool MetricsLog::HasEnvironment() const {
174 return uma_proto()->system_profile().has_uma_enabled_date();
177 bool MetricsLog::HasStabilityMetrics() const {
178 return uma_proto()->system_profile().stability().has_launch_count();
181 // The server refuses data that doesn't have certain values. crashcount and
182 // launchcount are currently "required" in the "stability" group.
183 // TODO(isherman): Stop writing these attributes specially once the migration to
184 // protobufs is complete.
185 void MetricsLog::WriteRequiredStabilityAttributes(PrefService* pref) {
186 int launch_count = pref->GetInteger(prefs::kStabilityLaunchCount);
187 pref->SetInteger(prefs::kStabilityLaunchCount, 0);
188 int crash_count = pref->GetInteger(prefs::kStabilityCrashCount);
189 pref->SetInteger(prefs::kStabilityCrashCount, 0);
191 SystemProfileProto::Stability* stability =
192 uma_proto()->mutable_system_profile()->mutable_stability();
193 stability->set_launch_count(launch_count);
194 stability->set_crash_count(crash_count);
197 void MetricsLog::WriteRealtimeStabilityAttributes(
198 PrefService* pref,
199 base::TimeDelta incremental_uptime,
200 base::TimeDelta uptime) {
201 // Update the stats which are critical for real-time stability monitoring.
202 // Since these are "optional," only list ones that are non-zero, as the counts
203 // are aggregated (summed) server side.
205 SystemProfileProto::Stability* stability =
206 uma_proto()->mutable_system_profile()->mutable_stability();
208 const uint64 incremental_uptime_sec = incremental_uptime.InSeconds();
209 if (incremental_uptime_sec)
210 stability->set_incremental_uptime_sec(incremental_uptime_sec);
211 const uint64 uptime_sec = uptime.InSeconds();
212 if (uptime_sec)
213 stability->set_uptime_sec(uptime_sec);
216 void MetricsLog::RecordEnvironment(
217 const std::vector<metrics::MetricsProvider*>& metrics_providers,
218 const std::vector<variations::ActiveGroupId>& synthetic_trials) {
219 DCHECK(!HasEnvironment());
221 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
223 std::string brand_code;
224 if (client_->GetBrand(&brand_code))
225 system_profile->set_brand_code(brand_code);
227 int enabled_date;
228 bool success =
229 base::StringToInt(GetMetricsEnabledDate(local_state_), &enabled_date);
230 DCHECK(success);
232 // Reduce granularity of the enabled_date field to nearest hour.
233 system_profile->set_uma_enabled_date(RoundSecondsToHour(enabled_date));
235 int64 install_date = local_state_->GetInt64(prefs::kInstallDate);
237 // Reduce granularity of the install_date field to nearest hour.
238 system_profile->set_install_date(RoundSecondsToHour(install_date));
240 system_profile->set_application_locale(client_->GetApplicationLocale());
242 SystemProfileProto::Hardware* hardware = system_profile->mutable_hardware();
244 // By default, the hardware class is empty (i.e., unknown).
245 hardware->set_hardware_class(std::string());
247 hardware->set_cpu_architecture(base::SysInfo::OperatingSystemArchitecture());
248 hardware->set_system_ram_mb(base::SysInfo::AmountOfPhysicalMemoryMB());
249 #if defined(OS_WIN)
250 hardware->set_dll_base(reinterpret_cast<uint64>(&__ImageBase));
251 #endif
253 SystemProfileProto::OS* os = system_profile->mutable_os();
254 std::string os_name = base::SysInfo::OperatingSystemName();
255 #if defined(OS_WIN)
256 // TODO(mad): This only checks whether the main process is a Metro process at
257 // upload time; not whether the collected metrics were all gathered from
258 // Metro. This is ok as an approximation for now, since users will rarely be
259 // switching from Metro to Desktop mode; but we should re-evaluate whether we
260 // can distinguish metrics more cleanly in the future: http://crbug.com/140568
261 if (base::win::IsMetroProcess())
262 os_name += " (Metro)";
263 #endif
264 os->set_name(os_name);
265 os->set_version(base::SysInfo::OperatingSystemVersion());
266 #if defined(OS_ANDROID)
267 os->set_fingerprint(
268 base::android::BuildInfo::GetInstance()->android_build_fp());
269 #endif
271 base::CPU cpu_info;
272 SystemProfileProto::Hardware::CPU* cpu = hardware->mutable_cpu();
273 cpu->set_vendor_name(cpu_info.vendor_name());
274 cpu->set_signature(cpu_info.signature());
276 std::vector<ActiveGroupId> field_trial_ids;
277 GetFieldTrialIds(&field_trial_ids);
278 WriteFieldTrials(field_trial_ids, system_profile);
279 WriteFieldTrials(synthetic_trials, system_profile);
281 for (size_t i = 0; i < metrics_providers.size(); ++i)
282 metrics_providers[i]->ProvideSystemProfileMetrics(system_profile);
284 std::string serialied_system_profile;
285 std::string base64_system_profile;
286 if (system_profile->SerializeToString(&serialied_system_profile)) {
287 base::Base64Encode(serialied_system_profile, &base64_system_profile);
288 PrefService* local_state = local_state_;
289 local_state->SetString(prefs::kStabilitySavedSystemProfile,
290 base64_system_profile);
291 local_state->SetString(prefs::kStabilitySavedSystemProfileHash,
292 ComputeSHA1(serialied_system_profile));
296 bool MetricsLog::LoadSavedEnvironmentFromPrefs() {
297 PrefService* local_state = local_state_;
298 const std::string base64_system_profile =
299 local_state->GetString(prefs::kStabilitySavedSystemProfile);
300 if (base64_system_profile.empty())
301 return false;
303 const std::string system_profile_hash =
304 local_state->GetString(prefs::kStabilitySavedSystemProfileHash);
305 local_state->ClearPref(prefs::kStabilitySavedSystemProfile);
306 local_state->ClearPref(prefs::kStabilitySavedSystemProfileHash);
308 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
309 std::string serialied_system_profile;
310 return base::Base64Decode(base64_system_profile, &serialied_system_profile) &&
311 ComputeSHA1(serialied_system_profile) == system_profile_hash &&
312 system_profile->ParseFromString(serialied_system_profile);