Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / components / metrics / metrics_log.cc
blob42dca83236b6c598701b448ca35f8dca7d53676b
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 // 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 MetricsServiceClient* client,
89 PrefService* local_state)
90 : closed_(false),
91 log_type_(log_type),
92 client_(client),
93 creation_time_(base::TimeTicks::Now()),
94 local_state_(local_state) {
95 if (IsTestingID(client_id))
96 uma_proto_.set_client_id(0);
97 else
98 uma_proto_.set_client_id(Hash(client_id));
100 uma_proto_.set_session_id(session_id);
102 const int32 product = client_->GetProduct();
103 // Only set the product if it differs from the default value.
104 if (product != uma_proto_.product())
105 uma_proto_.set_product(product);
107 SystemProfileProto* system_profile = uma_proto_.mutable_system_profile();
108 system_profile->set_build_timestamp(GetBuildTime());
109 system_profile->set_app_version(client_->GetVersionString());
110 system_profile->set_channel(client_->GetChannel());
111 #if defined(SYZYASAN)
112 system_profile->set_is_asan_build(true);
113 #endif
116 MetricsLog::~MetricsLog() {
119 // static
120 void MetricsLog::RegisterPrefs(PrefRegistrySimple* registry) {
121 registry->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
122 registry->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
123 registry->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount, 0);
124 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail, 0);
125 registry->RegisterIntegerPref(
126 prefs::kStabilityBreakpadRegistrationSuccess, 0);
127 registry->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
128 registry->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
129 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfile,
130 std::string());
131 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfileHash,
132 std::string());
135 // static
136 uint64 MetricsLog::Hash(const std::string& value) {
137 uint64 hash = HashMetricName(value);
139 // The following log is VERY helpful when folks add some named histogram into
140 // the code, but forgot to update the descriptive list of histograms. When
141 // that happens, all we get to see (server side) is a hash of the histogram
142 // name. We can then use this logging to find out what histogram name was
143 // being hashed to a given MD5 value by just running the version of Chromium
144 // in question with --enable-logging.
145 DVLOG(1) << "Metrics: Hash numeric [" << value << "]=[" << hash << "]";
147 return hash;
150 // static
151 int64 MetricsLog::GetBuildTime() {
152 static int64 integral_build_time = 0;
153 if (!integral_build_time)
154 integral_build_time = static_cast<int64>(base::GetBuildTime().ToTimeT());
155 return integral_build_time;
158 // static
159 int64 MetricsLog::GetCurrentTime() {
160 return (base::TimeTicks::Now() - base::TimeTicks()).InSeconds();
163 void MetricsLog::RecordUserAction(const std::string& key) {
164 DCHECK(!closed_);
166 UserActionEventProto* user_action = uma_proto_.add_user_action_event();
167 user_action->set_name_hash(Hash(key));
168 user_action->set_time(GetCurrentTime());
171 void MetricsLog::RecordHistogramDelta(const std::string& histogram_name,
172 const base::HistogramSamples& snapshot) {
173 DCHECK(!closed_);
174 EncodeHistogramDelta(histogram_name, snapshot, &uma_proto_);
177 void MetricsLog::RecordStabilityMetrics(
178 const std::vector<MetricsProvider*>& metrics_providers,
179 base::TimeDelta incremental_uptime,
180 base::TimeDelta uptime) {
181 DCHECK(!closed_);
182 DCHECK(HasEnvironment());
183 DCHECK(!HasStabilityMetrics());
185 PrefService* pref = local_state_;
186 DCHECK(pref);
188 // Get stability attributes out of Local State, zeroing out stored values.
189 // NOTE: This could lead to some data loss if this report isn't successfully
190 // sent, but that's true for all the metrics.
192 WriteRequiredStabilityAttributes(pref);
194 // Record recent delta for critical stability metrics. We can't wait for a
195 // restart to gather these, as that delay biases our observation away from
196 // users that run happily for a looooong time. We send increments with each
197 // uma log upload, just as we send histogram data.
198 WriteRealtimeStabilityAttributes(pref, incremental_uptime, uptime);
200 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
201 for (size_t i = 0; i < metrics_providers.size(); ++i)
202 metrics_providers[i]->ProvideStabilityMetrics(system_profile);
204 // Omit some stats unless this is the initial stability log.
205 if (log_type() != INITIAL_STABILITY_LOG)
206 return;
208 int incomplete_shutdown_count =
209 pref->GetInteger(prefs::kStabilityIncompleteSessionEndCount);
210 pref->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
211 int breakpad_registration_success_count =
212 pref->GetInteger(prefs::kStabilityBreakpadRegistrationSuccess);
213 pref->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
214 int breakpad_registration_failure_count =
215 pref->GetInteger(prefs::kStabilityBreakpadRegistrationFail);
216 pref->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
217 int debugger_present_count =
218 pref->GetInteger(prefs::kStabilityDebuggerPresent);
219 pref->SetInteger(prefs::kStabilityDebuggerPresent, 0);
220 int debugger_not_present_count =
221 pref->GetInteger(prefs::kStabilityDebuggerNotPresent);
222 pref->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
224 // TODO(jar): The following are all optional, so we *could* optimize them for
225 // values of zero (and not include them).
226 SystemProfileProto::Stability* stability =
227 system_profile->mutable_stability();
228 stability->set_incomplete_shutdown_count(incomplete_shutdown_count);
229 stability->set_breakpad_registration_success_count(
230 breakpad_registration_success_count);
231 stability->set_breakpad_registration_failure_count(
232 breakpad_registration_failure_count);
233 stability->set_debugger_present_count(debugger_present_count);
234 stability->set_debugger_not_present_count(debugger_not_present_count);
237 void MetricsLog::RecordGeneralMetrics(
238 const std::vector<MetricsProvider*>& metrics_providers) {
239 for (size_t i = 0; i < metrics_providers.size(); ++i)
240 metrics_providers[i]->ProvideGeneralMetrics(uma_proto());
243 void MetricsLog::GetFieldTrialIds(
244 std::vector<ActiveGroupId>* field_trial_ids) const {
245 variations::GetFieldTrialActiveGroupIds(field_trial_ids);
248 bool MetricsLog::HasEnvironment() const {
249 return uma_proto()->system_profile().has_uma_enabled_date();
252 bool MetricsLog::HasStabilityMetrics() const {
253 return uma_proto()->system_profile().stability().has_launch_count();
256 // The server refuses data that doesn't have certain values. crashcount and
257 // launchcount are currently "required" in the "stability" group.
258 // TODO(isherman): Stop writing these attributes specially once the migration to
259 // protobufs is complete.
260 void MetricsLog::WriteRequiredStabilityAttributes(PrefService* pref) {
261 int launch_count = pref->GetInteger(prefs::kStabilityLaunchCount);
262 pref->SetInteger(prefs::kStabilityLaunchCount, 0);
263 int crash_count = pref->GetInteger(prefs::kStabilityCrashCount);
264 pref->SetInteger(prefs::kStabilityCrashCount, 0);
266 SystemProfileProto::Stability* stability =
267 uma_proto()->mutable_system_profile()->mutable_stability();
268 stability->set_launch_count(launch_count);
269 stability->set_crash_count(crash_count);
272 void MetricsLog::WriteRealtimeStabilityAttributes(
273 PrefService* pref,
274 base::TimeDelta incremental_uptime,
275 base::TimeDelta uptime) {
276 // Update the stats which are critical for real-time stability monitoring.
277 // Since these are "optional," only list ones that are non-zero, as the counts
278 // are aggregated (summed) server side.
280 SystemProfileProto::Stability* stability =
281 uma_proto()->mutable_system_profile()->mutable_stability();
283 const uint64 incremental_uptime_sec = incremental_uptime.InSeconds();
284 if (incremental_uptime_sec)
285 stability->set_incremental_uptime_sec(incremental_uptime_sec);
286 const uint64 uptime_sec = uptime.InSeconds();
287 if (uptime_sec)
288 stability->set_uptime_sec(uptime_sec);
291 void MetricsLog::RecordEnvironment(
292 const std::vector<MetricsProvider*>& metrics_providers,
293 const std::vector<variations::ActiveGroupId>& synthetic_trials,
294 int64 install_date,
295 int64 metrics_reporting_enabled_date) {
296 DCHECK(!HasEnvironment());
298 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
300 std::string brand_code;
301 if (client_->GetBrand(&brand_code))
302 system_profile->set_brand_code(brand_code);
304 // Reduce granularity of the enabled_date field to nearest hour.
305 system_profile->set_uma_enabled_date(
306 RoundSecondsToHour(metrics_reporting_enabled_date));
308 // Reduce granularity of the install_date field to nearest hour.
309 system_profile->set_install_date(RoundSecondsToHour(install_date));
311 system_profile->set_application_locale(client_->GetApplicationLocale());
313 SystemProfileProto::Hardware* hardware = system_profile->mutable_hardware();
315 // HardwareModelName() will return an empty string on platforms where it's
316 // not implemented or if an error occured.
317 hardware->set_hardware_class(base::SysInfo::HardwareModelName());
319 hardware->set_cpu_architecture(base::SysInfo::OperatingSystemArchitecture());
320 hardware->set_system_ram_mb(base::SysInfo::AmountOfPhysicalMemoryMB());
321 #if defined(OS_WIN)
322 hardware->set_dll_base(reinterpret_cast<uint64>(&__ImageBase));
323 #endif
325 SystemProfileProto::OS* os = system_profile->mutable_os();
326 std::string os_name = base::SysInfo::OperatingSystemName();
327 #if defined(OS_WIN)
328 // TODO(mad): This only checks whether the main process is a Metro process at
329 // upload time; not whether the collected metrics were all gathered from
330 // Metro. This is ok as an approximation for now, since users will rarely be
331 // switching from Metro to Desktop mode; but we should re-evaluate whether we
332 // can distinguish metrics more cleanly in the future: http://crbug.com/140568
333 if (base::win::IsMetroProcess())
334 os_name += " (Metro)";
335 #endif
336 os->set_name(os_name);
337 os->set_version(base::SysInfo::OperatingSystemVersion());
338 #if defined(OS_ANDROID)
339 os->set_fingerprint(
340 base::android::BuildInfo::GetInstance()->android_build_fp());
341 #endif
343 base::CPU cpu_info;
344 SystemProfileProto::Hardware::CPU* cpu = hardware->mutable_cpu();
345 cpu->set_vendor_name(cpu_info.vendor_name());
346 cpu->set_signature(cpu_info.signature());
347 cpu->set_num_cores(base::SysInfo::NumberOfProcessors());
349 std::vector<ActiveGroupId> field_trial_ids;
350 GetFieldTrialIds(&field_trial_ids);
351 WriteFieldTrials(field_trial_ids, system_profile);
352 WriteFieldTrials(synthetic_trials, system_profile);
354 for (size_t i = 0; i < metrics_providers.size(); ++i)
355 metrics_providers[i]->ProvideSystemProfileMetrics(system_profile);
357 std::string serialied_system_profile;
358 std::string base64_system_profile;
359 if (system_profile->SerializeToString(&serialied_system_profile)) {
360 base::Base64Encode(serialied_system_profile, &base64_system_profile);
361 PrefService* local_state = local_state_;
362 local_state->SetString(prefs::kStabilitySavedSystemProfile,
363 base64_system_profile);
364 local_state->SetString(prefs::kStabilitySavedSystemProfileHash,
365 ComputeSHA1(serialied_system_profile));
369 bool MetricsLog::LoadSavedEnvironmentFromPrefs() {
370 PrefService* local_state = local_state_;
371 const std::string base64_system_profile =
372 local_state->GetString(prefs::kStabilitySavedSystemProfile);
373 if (base64_system_profile.empty())
374 return false;
376 const std::string system_profile_hash =
377 local_state->GetString(prefs::kStabilitySavedSystemProfileHash);
378 local_state->ClearPref(prefs::kStabilitySavedSystemProfile);
379 local_state->ClearPref(prefs::kStabilitySavedSystemProfileHash);
381 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
382 std::string serialied_system_profile;
383 return base::Base64Decode(base64_system_profile, &serialied_system_profile) &&
384 ComputeSHA1(serialied_system_profile) == system_profile_hash &&
385 system_profile->ParseFromString(serialied_system_profile);
388 void MetricsLog::CloseLog() {
389 DCHECK(!closed_);
390 closed_ = true;
393 void MetricsLog::GetEncodedLog(std::string* encoded_log) {
394 DCHECK(closed_);
395 uma_proto_.SerializeToString(encoded_log);
398 } // namespace metrics