Files.app: make default-action as a command.
[chromium-blink-merge.git] / components / metrics / metrics_state_manager.cc
blob319311576ecab943f531455e8d90f59c665fb9c9
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_state_manager.h"
7 #include "base/command_line.h"
8 #include "base/guid.h"
9 #include "base/metrics/histogram_macros.h"
10 #include "base/metrics/sparse_histogram.h"
11 #include "base/prefs/pref_registry_simple.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/rand_util.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/threading/thread_restrictions.h"
16 #include "base/time/time.h"
17 #include "components/metrics/cloned_install_detector.h"
18 #include "components/metrics/machine_id_provider.h"
19 #include "components/metrics/metrics_pref_names.h"
20 #include "components/metrics/metrics_switches.h"
21 #include "components/variations/caching_permuted_entropy_provider.h"
23 namespace metrics {
25 namespace {
27 // The argument used to generate a non-identifying entropy source. We want no
28 // more than 13 bits of entropy, so use this max to return a number in the range
29 // [0, 7999] as the entropy source (12.97 bits of entropy).
30 const int kMaxLowEntropySize = 8000;
32 // Default prefs value for prefs::kMetricsLowEntropySource to indicate that
33 // the value has not yet been set.
34 const int kLowEntropySourceNotSet = -1;
36 // Generates a new non-identifying entropy source used to seed persistent
37 // activities.
38 int GenerateLowEntropySource() {
39 return base::RandInt(0, kMaxLowEntropySize - 1);
42 } // namespace
44 // static
45 bool MetricsStateManager::instance_exists_ = false;
47 MetricsStateManager::MetricsStateManager(
48 PrefService* local_state,
49 const base::Callback<bool(void)>& is_reporting_enabled_callback,
50 const StoreClientInfoCallback& store_client_info,
51 const LoadClientInfoCallback& retrieve_client_info)
52 : local_state_(local_state),
53 is_reporting_enabled_callback_(is_reporting_enabled_callback),
54 store_client_info_(store_client_info),
55 load_client_info_(retrieve_client_info),
56 low_entropy_source_(kLowEntropySourceNotSet),
57 entropy_source_returned_(ENTROPY_SOURCE_NONE) {
58 ResetMetricsIDsIfNecessary();
59 if (IsMetricsReportingEnabled())
60 ForceClientIdCreation();
62 DCHECK(!instance_exists_);
63 instance_exists_ = true;
66 MetricsStateManager::~MetricsStateManager() {
67 DCHECK(instance_exists_);
68 instance_exists_ = false;
71 bool MetricsStateManager::IsMetricsReportingEnabled() {
72 return is_reporting_enabled_callback_.Run();
75 void MetricsStateManager::ForceClientIdCreation() {
76 if (!client_id_.empty())
77 return;
79 client_id_ = local_state_->GetString(prefs::kMetricsClientID);
80 if (!client_id_.empty()) {
81 // It is technically sufficient to only save a backup of the client id when
82 // it is initially generated below, but since the backup was only introduced
83 // in M38, seed it explicitly from here for some time.
84 BackUpCurrentClientInfo();
85 return;
88 const scoped_ptr<ClientInfo> client_info_backup =
89 LoadClientInfoAndMaybeMigrate();
90 if (client_info_backup) {
91 client_id_ = client_info_backup->client_id;
93 const base::Time now = base::Time::Now();
95 // Save the recovered client id and also try to reinstantiate the backup
96 // values for the dates corresponding with that client id in order to avoid
97 // weird scenarios where we could report an old client id with a recent
98 // install date.
99 local_state_->SetString(prefs::kMetricsClientID, client_id_);
100 local_state_->SetInt64(prefs::kInstallDate,
101 client_info_backup->installation_date != 0
102 ? client_info_backup->installation_date
103 : now.ToTimeT());
104 local_state_->SetInt64(prefs::kMetricsReportingEnabledTimestamp,
105 client_info_backup->reporting_enabled_date != 0
106 ? client_info_backup->reporting_enabled_date
107 : now.ToTimeT());
109 base::TimeDelta recovered_installation_age;
110 if (client_info_backup->installation_date != 0) {
111 recovered_installation_age =
112 now - base::Time::FromTimeT(client_info_backup->installation_date);
114 UMA_HISTOGRAM_COUNTS_10000("UMA.ClientIdBackupRecoveredWithAge",
115 recovered_installation_age.InHours());
117 // Flush the backup back to persistent storage in case we re-generated
118 // missing data above.
119 BackUpCurrentClientInfo();
120 return;
123 // Failing attempts at getting an existing client ID, generate a new one.
124 client_id_ = base::GenerateGUID();
125 local_state_->SetString(prefs::kMetricsClientID, client_id_);
127 // Record the timestamp of when the user opted in to UMA.
128 local_state_->SetInt64(prefs::kMetricsReportingEnabledTimestamp,
129 base::Time::Now().ToTimeT());
131 BackUpCurrentClientInfo();
134 void MetricsStateManager::CheckForClonedInstall(
135 scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
136 DCHECK(!cloned_install_detector_);
138 MachineIdProvider* provider = MachineIdProvider::CreateInstance();
139 if (!provider)
140 return;
142 cloned_install_detector_.reset(new ClonedInstallDetector(provider));
143 cloned_install_detector_->CheckForClonedInstall(local_state_, task_runner);
146 scoped_ptr<const base::FieldTrial::EntropyProvider>
147 MetricsStateManager::CreateEntropyProvider() {
148 // For metrics reporting-enabled users, we combine the client ID and low
149 // entropy source to get the final entropy source. Otherwise, only use the low
150 // entropy source.
151 // This has two useful properties:
152 // 1) It makes the entropy source less identifiable for parties that do not
153 // know the low entropy source.
154 // 2) It makes the final entropy source resettable.
155 const int low_entropy_source_value = GetLowEntropySource();
156 UMA_HISTOGRAM_SPARSE_SLOWLY("UMA.LowEntropySourceValue",
157 low_entropy_source_value);
158 if (IsMetricsReportingEnabled()) {
159 UpdateEntropySourceReturnedValue(ENTROPY_SOURCE_HIGH);
160 const std::string high_entropy_source =
161 client_id_ + base::IntToString(low_entropy_source_value);
162 return scoped_ptr<const base::FieldTrial::EntropyProvider>(
163 new SHA1EntropyProvider(high_entropy_source));
166 UpdateEntropySourceReturnedValue(ENTROPY_SOURCE_LOW);
167 #if defined(OS_ANDROID) || defined(OS_IOS)
168 return scoped_ptr<const base::FieldTrial::EntropyProvider>(
169 new CachingPermutedEntropyProvider(local_state_,
170 low_entropy_source_value,
171 kMaxLowEntropySize));
172 #else
173 return scoped_ptr<const base::FieldTrial::EntropyProvider>(
174 new PermutedEntropyProvider(low_entropy_source_value,
175 kMaxLowEntropySize));
176 #endif
179 // static
180 scoped_ptr<MetricsStateManager> MetricsStateManager::Create(
181 PrefService* local_state,
182 const base::Callback<bool(void)>& is_reporting_enabled_callback,
183 const StoreClientInfoCallback& store_client_info,
184 const LoadClientInfoCallback& retrieve_client_info) {
185 scoped_ptr<MetricsStateManager> result;
186 // Note: |instance_exists_| is updated in the constructor and destructor.
187 if (!instance_exists_) {
188 result.reset(new MetricsStateManager(local_state,
189 is_reporting_enabled_callback,
190 store_client_info,
191 retrieve_client_info));
193 return result.Pass();
196 // static
197 void MetricsStateManager::RegisterPrefs(PrefRegistrySimple* registry) {
198 registry->RegisterBooleanPref(prefs::kMetricsResetIds, false);
199 registry->RegisterStringPref(prefs::kMetricsClientID, std::string());
200 registry->RegisterInt64Pref(prefs::kMetricsReportingEnabledTimestamp, 0);
201 registry->RegisterIntegerPref(prefs::kMetricsLowEntropySource,
202 kLowEntropySourceNotSet);
204 ClonedInstallDetector::RegisterPrefs(registry);
205 CachingPermutedEntropyProvider::RegisterPrefs(registry);
208 void MetricsStateManager::BackUpCurrentClientInfo() {
209 ClientInfo client_info;
210 client_info.client_id = client_id_;
211 client_info.installation_date = local_state_->GetInt64(prefs::kInstallDate);
212 client_info.reporting_enabled_date =
213 local_state_->GetInt64(prefs::kMetricsReportingEnabledTimestamp);
214 store_client_info_.Run(client_info);
217 scoped_ptr<ClientInfo> MetricsStateManager::LoadClientInfoAndMaybeMigrate() {
218 scoped_ptr<ClientInfo> client_info = load_client_info_.Run();
220 // Prior to 2014-07, the client ID was stripped of its dashes before being
221 // saved. Migrate back to a proper GUID if this is the case. This migration
222 // code can be removed in M41+.
223 const size_t kGUIDLengthWithoutDashes = 32U;
224 if (client_info &&
225 client_info->client_id.length() == kGUIDLengthWithoutDashes) {
226 DCHECK(client_info->client_id.find('-') == std::string::npos);
228 std::string client_id_with_dashes;
229 client_id_with_dashes.reserve(kGUIDLengthWithoutDashes + 4U);
230 std::string::const_iterator client_id_it = client_info->client_id.begin();
231 for (size_t i = 0; i < kGUIDLengthWithoutDashes + 4U; ++i) {
232 if (i == 8U || i == 13U || i == 18U || i == 23U) {
233 client_id_with_dashes.push_back('-');
234 } else {
235 client_id_with_dashes.push_back(*client_id_it);
236 ++client_id_it;
239 DCHECK(client_id_it == client_info->client_id.end());
240 client_info->client_id.assign(client_id_with_dashes);
243 // The GUID retrieved (and possibly fixed above) should be valid unless
244 // retrieval failed.
245 DCHECK(!client_info || base::IsValidGUID(client_info->client_id));
247 return client_info.Pass();
250 int MetricsStateManager::GetLowEntropySource() {
251 // Note that the default value for the low entropy source and the default pref
252 // value are both kLowEntropySourceNotSet, which is used to identify if the
253 // value has been set or not.
254 if (low_entropy_source_ != kLowEntropySourceNotSet)
255 return low_entropy_source_;
257 const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess());
258 // Only try to load the value from prefs if the user did not request a
259 // reset.
260 // Otherwise, skip to generating a new value.
261 if (!command_line->HasSwitch(switches::kResetVariationState)) {
262 int value = local_state_->GetInteger(prefs::kMetricsLowEntropySource);
263 // If the value is outside the [0, kMaxLowEntropySize) range, re-generate
264 // it below.
265 if (value >= 0 && value < kMaxLowEntropySize) {
266 low_entropy_source_ = value;
267 UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", false);
268 return low_entropy_source_;
272 UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", true);
273 low_entropy_source_ = GenerateLowEntropySource();
274 local_state_->SetInteger(prefs::kMetricsLowEntropySource,
275 low_entropy_source_);
276 CachingPermutedEntropyProvider::ClearCache(local_state_);
278 return low_entropy_source_;
281 void MetricsStateManager::UpdateEntropySourceReturnedValue(
282 EntropySourceType type) {
283 if (entropy_source_returned_ != ENTROPY_SOURCE_NONE)
284 return;
286 entropy_source_returned_ = type;
287 UMA_HISTOGRAM_ENUMERATION("UMA.EntropySourceType", type,
288 ENTROPY_SOURCE_ENUM_SIZE);
291 void MetricsStateManager::ResetMetricsIDsIfNecessary() {
292 if (!local_state_->GetBoolean(prefs::kMetricsResetIds))
293 return;
295 UMA_HISTOGRAM_BOOLEAN("UMA.MetricsIDsReset", true);
297 DCHECK(client_id_.empty());
298 DCHECK_EQ(kLowEntropySourceNotSet, low_entropy_source_);
300 local_state_->ClearPref(prefs::kMetricsClientID);
301 local_state_->ClearPref(prefs::kMetricsLowEntropySource);
302 local_state_->ClearPref(prefs::kMetricsResetIds);
304 // Also clear the backed up client info.
305 store_client_info_.Run(ClientInfo());
308 } // namespace metrics