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"
11 #include "base/base64.h"
12 #include "base/basictypes.h"
13 #include "base/build_time.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/metrics_hashes.h"
27 #include "components/metrics/metrics_pref_names.h"
28 #include "components/metrics/metrics_provider.h"
29 #include "components/metrics/metrics_service_client.h"
30 #include "components/metrics/proto/histogram_event.pb.h"
31 #include "components/metrics/proto/system_profile.pb.h"
32 #include "components/metrics/proto/user_action_event.pb.h"
33 #include "components/variations/active_field_trials.h"
35 #if defined(OS_ANDROID)
36 #include "base/android/build_info.h"
40 #include "base/win/metro.h"
42 // http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
43 extern "C" IMAGE_DOS_HEADER __ImageBase
;
46 using base::SampleCountIterator
;
47 typedef variations::ActiveGroupId ActiveGroupId
;
53 // Any id less than 16 bytes is considered to be a testing id.
54 bool IsTestingID(const std::string
& id
) {
55 return id
.size() < 16;
58 // Returns the date at which the current metrics client ID was created as
59 // a string containing seconds since the epoch, or "0" if none was found.
60 std::string
GetMetricsEnabledDate(PrefService
* pref
) {
66 return pref
->GetString(prefs::kMetricsReportingEnabledTimestamp
);
69 // Computes a SHA-1 hash of |data| and returns it as a hex string.
70 std::string
ComputeSHA1(const std::string
& data
) {
71 const std::string sha1
= base::SHA1HashString(data
);
72 return base::HexEncode(sha1
.data(), sha1
.size());
75 void WriteFieldTrials(const std::vector
<ActiveGroupId
>& field_trial_ids
,
76 SystemProfileProto
* system_profile
) {
77 for (std::vector
<ActiveGroupId
>::const_iterator it
=
78 field_trial_ids
.begin(); it
!= field_trial_ids
.end(); ++it
) {
79 SystemProfileProto::FieldTrial
* field_trial
=
80 system_profile
->add_field_trial();
81 field_trial
->set_name_id(it
->name
);
82 field_trial
->set_group_id(it
->group
);
86 // Round a timestamp measured in seconds since epoch to one with a granularity
87 // of an hour. This can be used before uploaded potentially sensitive
89 int64
RoundSecondsToHour(int64 time_in_seconds
) {
90 return 3600 * (time_in_seconds
/ 3600);
95 MetricsLog::MetricsLog(const std::string
& client_id
,
98 MetricsServiceClient
* client
,
99 PrefService
* local_state
)
103 creation_time_(base::TimeTicks::Now()),
104 local_state_(local_state
) {
105 if (IsTestingID(client_id
))
106 uma_proto_
.set_client_id(0);
108 uma_proto_
.set_client_id(Hash(client_id
));
110 uma_proto_
.set_session_id(session_id
);
112 const int32 product
= client_
->GetProduct();
113 // Only set the product if it differs from the default value.
114 if (product
!= uma_proto_
.product())
115 uma_proto_
.set_product(product
);
117 SystemProfileProto
* system_profile
= uma_proto_
.mutable_system_profile();
118 system_profile
->set_build_timestamp(GetBuildTime());
119 system_profile
->set_app_version(client_
->GetVersionString());
120 system_profile
->set_channel(client_
->GetChannel());
123 MetricsLog::~MetricsLog() {
127 void MetricsLog::RegisterPrefs(PrefRegistrySimple
* registry
) {
128 registry
->RegisterIntegerPref(prefs::kStabilityLaunchCount
, 0);
129 registry
->RegisterIntegerPref(prefs::kStabilityCrashCount
, 0);
130 registry
->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount
, 0);
131 registry
->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail
, 0);
132 registry
->RegisterIntegerPref(
133 prefs::kStabilityBreakpadRegistrationSuccess
, 0);
134 registry
->RegisterIntegerPref(prefs::kStabilityDebuggerPresent
, 0);
135 registry
->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent
, 0);
136 registry
->RegisterStringPref(prefs::kStabilitySavedSystemProfile
,
138 registry
->RegisterStringPref(prefs::kStabilitySavedSystemProfileHash
,
143 uint64
MetricsLog::Hash(const std::string
& value
) {
144 uint64 hash
= HashMetricName(value
);
146 // The following log is VERY helpful when folks add some named histogram into
147 // the code, but forgot to update the descriptive list of histograms. When
148 // that happens, all we get to see (server side) is a hash of the histogram
149 // name. We can then use this logging to find out what histogram name was
150 // being hashed to a given MD5 value by just running the version of Chromium
151 // in question with --enable-logging.
152 DVLOG(1) << "Metrics: Hash numeric [" << value
<< "]=[" << hash
<< "]";
158 int64
MetricsLog::GetBuildTime() {
159 static int64 integral_build_time
= 0;
160 if (!integral_build_time
)
161 integral_build_time
= static_cast<int64
>(base::GetBuildTime().ToTimeT());
162 return integral_build_time
;
166 int64
MetricsLog::GetCurrentTime() {
167 return (base::TimeTicks::Now() - base::TimeTicks()).InSeconds();
170 void MetricsLog::RecordUserAction(const std::string
& key
) {
173 UserActionEventProto
* user_action
= uma_proto_
.add_user_action_event();
174 user_action
->set_name_hash(Hash(key
));
175 user_action
->set_time(GetCurrentTime());
178 void MetricsLog::RecordHistogramDelta(const std::string
& histogram_name
,
179 const base::HistogramSamples
& snapshot
) {
181 DCHECK_NE(0, snapshot
.TotalCount());
183 // We will ignore the MAX_INT/infinite value in the last element of range[].
185 HistogramEventProto
* histogram_proto
= uma_proto_
.add_histogram_event();
186 histogram_proto
->set_name_hash(Hash(histogram_name
));
187 histogram_proto
->set_sum(snapshot
.sum());
189 for (scoped_ptr
<SampleCountIterator
> it
= snapshot
.Iterator(); !it
->Done();
191 base::Histogram::Sample min
;
192 base::Histogram::Sample max
;
193 base::Histogram::Count count
;
194 it
->Get(&min
, &max
, &count
);
195 HistogramEventProto::Bucket
* bucket
= histogram_proto
->add_bucket();
196 bucket
->set_min(min
);
197 bucket
->set_max(max
);
198 bucket
->set_count(count
);
201 // Omit fields to save space (see rules in histogram_event.proto comments).
202 for (int i
= 0; i
< histogram_proto
->bucket_size(); ++i
) {
203 HistogramEventProto::Bucket
* bucket
= histogram_proto
->mutable_bucket(i
);
204 if (i
+ 1 < histogram_proto
->bucket_size() &&
205 bucket
->max() == histogram_proto
->bucket(i
+ 1).min()) {
207 } else if (bucket
->max() == bucket
->min() + 1) {
213 void MetricsLog::RecordStabilityMetrics(
214 const std::vector
<MetricsProvider
*>& metrics_providers
,
215 base::TimeDelta incremental_uptime
,
216 base::TimeDelta uptime
) {
218 DCHECK(HasEnvironment());
219 DCHECK(!HasStabilityMetrics());
221 PrefService
* pref
= local_state_
;
224 // Get stability attributes out of Local State, zeroing out stored values.
225 // NOTE: This could lead to some data loss if this report isn't successfully
226 // sent, but that's true for all the metrics.
228 WriteRequiredStabilityAttributes(pref
);
230 // Record recent delta for critical stability metrics. We can't wait for a
231 // restart to gather these, as that delay biases our observation away from
232 // users that run happily for a looooong time. We send increments with each
233 // uma log upload, just as we send histogram data.
234 WriteRealtimeStabilityAttributes(pref
, incremental_uptime
, uptime
);
236 SystemProfileProto
* system_profile
= uma_proto()->mutable_system_profile();
237 for (size_t i
= 0; i
< metrics_providers
.size(); ++i
)
238 metrics_providers
[i
]->ProvideStabilityMetrics(system_profile
);
240 // Omit some stats unless this is the initial stability log.
241 if (log_type() != INITIAL_STABILITY_LOG
)
244 int incomplete_shutdown_count
=
245 pref
->GetInteger(prefs::kStabilityIncompleteSessionEndCount
);
246 pref
->SetInteger(prefs::kStabilityIncompleteSessionEndCount
, 0);
247 int breakpad_registration_success_count
=
248 pref
->GetInteger(prefs::kStabilityBreakpadRegistrationSuccess
);
249 pref
->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess
, 0);
250 int breakpad_registration_failure_count
=
251 pref
->GetInteger(prefs::kStabilityBreakpadRegistrationFail
);
252 pref
->SetInteger(prefs::kStabilityBreakpadRegistrationFail
, 0);
253 int debugger_present_count
=
254 pref
->GetInteger(prefs::kStabilityDebuggerPresent
);
255 pref
->SetInteger(prefs::kStabilityDebuggerPresent
, 0);
256 int debugger_not_present_count
=
257 pref
->GetInteger(prefs::kStabilityDebuggerNotPresent
);
258 pref
->SetInteger(prefs::kStabilityDebuggerNotPresent
, 0);
260 // TODO(jar): The following are all optional, so we *could* optimize them for
261 // values of zero (and not include them).
262 SystemProfileProto::Stability
* stability
=
263 system_profile
->mutable_stability();
264 stability
->set_incomplete_shutdown_count(incomplete_shutdown_count
);
265 stability
->set_breakpad_registration_success_count(
266 breakpad_registration_success_count
);
267 stability
->set_breakpad_registration_failure_count(
268 breakpad_registration_failure_count
);
269 stability
->set_debugger_present_count(debugger_present_count
);
270 stability
->set_debugger_not_present_count(debugger_not_present_count
);
273 void MetricsLog::RecordGeneralMetrics(
274 const std::vector
<MetricsProvider
*>& metrics_providers
) {
275 for (size_t i
= 0; i
< metrics_providers
.size(); ++i
)
276 metrics_providers
[i
]->ProvideGeneralMetrics(uma_proto());
279 void MetricsLog::GetFieldTrialIds(
280 std::vector
<ActiveGroupId
>* field_trial_ids
) const {
281 variations::GetFieldTrialActiveGroupIds(field_trial_ids
);
284 bool MetricsLog::HasEnvironment() const {
285 return uma_proto()->system_profile().has_uma_enabled_date();
288 bool MetricsLog::HasStabilityMetrics() const {
289 return uma_proto()->system_profile().stability().has_launch_count();
292 // The server refuses data that doesn't have certain values. crashcount and
293 // launchcount are currently "required" in the "stability" group.
294 // TODO(isherman): Stop writing these attributes specially once the migration to
295 // protobufs is complete.
296 void MetricsLog::WriteRequiredStabilityAttributes(PrefService
* pref
) {
297 int launch_count
= pref
->GetInteger(prefs::kStabilityLaunchCount
);
298 pref
->SetInteger(prefs::kStabilityLaunchCount
, 0);
299 int crash_count
= pref
->GetInteger(prefs::kStabilityCrashCount
);
300 pref
->SetInteger(prefs::kStabilityCrashCount
, 0);
302 SystemProfileProto::Stability
* stability
=
303 uma_proto()->mutable_system_profile()->mutable_stability();
304 stability
->set_launch_count(launch_count
);
305 stability
->set_crash_count(crash_count
);
308 void MetricsLog::WriteRealtimeStabilityAttributes(
310 base::TimeDelta incremental_uptime
,
311 base::TimeDelta uptime
) {
312 // Update the stats which are critical for real-time stability monitoring.
313 // Since these are "optional," only list ones that are non-zero, as the counts
314 // are aggregated (summed) server side.
316 SystemProfileProto::Stability
* stability
=
317 uma_proto()->mutable_system_profile()->mutable_stability();
319 const uint64 incremental_uptime_sec
= incremental_uptime
.InSeconds();
320 if (incremental_uptime_sec
)
321 stability
->set_incremental_uptime_sec(incremental_uptime_sec
);
322 const uint64 uptime_sec
= uptime
.InSeconds();
324 stability
->set_uptime_sec(uptime_sec
);
327 void MetricsLog::RecordEnvironment(
328 const std::vector
<MetricsProvider
*>& metrics_providers
,
329 const std::vector
<variations::ActiveGroupId
>& synthetic_trials
,
330 int64 install_date
) {
331 DCHECK(!HasEnvironment());
333 SystemProfileProto
* system_profile
= uma_proto()->mutable_system_profile();
335 std::string brand_code
;
336 if (client_
->GetBrand(&brand_code
))
337 system_profile
->set_brand_code(brand_code
);
341 base::StringToInt(GetMetricsEnabledDate(local_state_
), &enabled_date
);
344 // Reduce granularity of the enabled_date field to nearest hour.
345 system_profile
->set_uma_enabled_date(RoundSecondsToHour(enabled_date
));
347 // Reduce granularity of the install_date field to nearest hour.
348 system_profile
->set_install_date(RoundSecondsToHour(install_date
));
350 system_profile
->set_application_locale(client_
->GetApplicationLocale());
352 SystemProfileProto::Hardware
* hardware
= system_profile
->mutable_hardware();
354 // HardwareModelName() will return an empty string on platforms where it's
355 // not implemented or if an error occured.
356 hardware
->set_hardware_class(base::SysInfo::HardwareModelName());
358 hardware
->set_cpu_architecture(base::SysInfo::OperatingSystemArchitecture());
359 hardware
->set_system_ram_mb(base::SysInfo::AmountOfPhysicalMemoryMB());
361 hardware
->set_dll_base(reinterpret_cast<uint64
>(&__ImageBase
));
364 SystemProfileProto::OS
* os
= system_profile
->mutable_os();
365 std::string os_name
= base::SysInfo::OperatingSystemName();
367 // TODO(mad): This only checks whether the main process is a Metro process at
368 // upload time; not whether the collected metrics were all gathered from
369 // Metro. This is ok as an approximation for now, since users will rarely be
370 // switching from Metro to Desktop mode; but we should re-evaluate whether we
371 // can distinguish metrics more cleanly in the future: http://crbug.com/140568
372 if (base::win::IsMetroProcess())
373 os_name
+= " (Metro)";
375 os
->set_name(os_name
);
376 os
->set_version(base::SysInfo::OperatingSystemVersion());
377 #if defined(OS_ANDROID)
379 base::android::BuildInfo::GetInstance()->android_build_fp());
383 SystemProfileProto::Hardware::CPU
* cpu
= hardware
->mutable_cpu();
384 cpu
->set_vendor_name(cpu_info
.vendor_name());
385 cpu
->set_signature(cpu_info
.signature());
387 std::vector
<ActiveGroupId
> field_trial_ids
;
388 GetFieldTrialIds(&field_trial_ids
);
389 WriteFieldTrials(field_trial_ids
, system_profile
);
390 WriteFieldTrials(synthetic_trials
, system_profile
);
392 for (size_t i
= 0; i
< metrics_providers
.size(); ++i
)
393 metrics_providers
[i
]->ProvideSystemProfileMetrics(system_profile
);
395 std::string serialied_system_profile
;
396 std::string base64_system_profile
;
397 if (system_profile
->SerializeToString(&serialied_system_profile
)) {
398 base::Base64Encode(serialied_system_profile
, &base64_system_profile
);
399 PrefService
* local_state
= local_state_
;
400 local_state
->SetString(prefs::kStabilitySavedSystemProfile
,
401 base64_system_profile
);
402 local_state
->SetString(prefs::kStabilitySavedSystemProfileHash
,
403 ComputeSHA1(serialied_system_profile
));
407 bool MetricsLog::LoadSavedEnvironmentFromPrefs() {
408 PrefService
* local_state
= local_state_
;
409 const std::string base64_system_profile
=
410 local_state
->GetString(prefs::kStabilitySavedSystemProfile
);
411 if (base64_system_profile
.empty())
414 const std::string system_profile_hash
=
415 local_state
->GetString(prefs::kStabilitySavedSystemProfileHash
);
416 local_state
->ClearPref(prefs::kStabilitySavedSystemProfile
);
417 local_state
->ClearPref(prefs::kStabilitySavedSystemProfileHash
);
419 SystemProfileProto
* system_profile
= uma_proto()->mutable_system_profile();
420 std::string serialied_system_profile
;
421 return base::Base64Decode(base64_system_profile
, &serialied_system_profile
) &&
422 ComputeSHA1(serialied_system_profile
) == system_profile_hash
&&
423 system_profile
->ParseFromString(serialied_system_profile
);
426 void MetricsLog::CloseLog() {
431 void MetricsLog::GetEncodedLog(std::string
* encoded_log
) {
433 uma_proto_
.SerializeToString(encoded_log
);
436 } // namespace metrics