Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(35)

Side by Side Diff: chrome/installer/util/experiment_storage.cc

Issue 2889323004: Win 10 Inactive toast experiment metrics and storage modifications. (Closed)
Patch Set: Apply review comments Created 3 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2017 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.
4
5 #include "chrome/installer/util/experiment_storage.h"
6
7 #include <windows.h>
8
9 #include <stdint.h>
10
11 #include <limits>
12 #include <string>
13
14 #include "base/base64.h"
15 #include "base/bind.h"
16 #include "base/bind_helpers.h"
17 #include "base/logging.h"
18 #include "base/memory/ptr_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/task_scheduler/post_task.h"
21 #include "base/task_scheduler/task_traits.h"
22 #include "base/time/time.h"
23 #include "base/win/registry.h"
24 #include "base/win/win_util.h"
25 #include "chrome/install_static/install_details.h"
26 #include "chrome/install_static/install_modes.h"
27 #include "chrome/install_static/install_util.h"
28 #include "chrome/installer/util/experiment.h"
29 #include "chrome/installer/util/experiment_labels.h"
30 #include "chrome/installer/util/experiment_metrics.h"
31 #include "chrome/installer/util/google_update_settings.h"
32 #include "chrome/installer/util/shell_util.h"
33
34 namespace installer {
35
36 namespace {
37
38 constexpr base::char16 kExperimentLabelName[] = L"CrExp60";
39 constexpr wchar_t kRegKeyRetention[] = L"\\Retention";
40 constexpr wchar_t kRegValueActionDelay[] = L"ActionDelay";
41 constexpr wchar_t kRegValueFirstDisplayTime[] = L"FirstDisplayTime";
42 constexpr wchar_t kRegValueGroup[] = L"Group";
43 constexpr wchar_t kRegValueInactiveDays[] = L"InactiveDays";
44 constexpr wchar_t kRegValueLatestDisplayTime[] = L"LatestDisplayTime";
45 constexpr wchar_t kRegValueRetentionStudy[] = L"RetentionStudy";
46 constexpr wchar_t kRegValueState[] = L"State";
47 constexpr wchar_t kRegValueToastCount[] = L"ToastCount";
48 constexpr wchar_t kRegValueToastLocation[] = L"ToastLocation";
49 constexpr wchar_t kRegValueUserSessionUptime[] = L"UserSessionUptime";
50
51 constexpr int kSessionLengthBucketLowestBit = 0;
52 constexpr int kActionDelayBucketLowestBit =
53 ExperimentMetrics::kSessionLengthBucketBits + kSessionLengthBucketLowestBit;
54 constexpr int kLastUsedBucketLowestBit =
55 ExperimentMetrics::kActionDelayBucketBits + kActionDelayBucketLowestBit;
56 constexpr int kToastHourLowestBit =
57 ExperimentMetrics::kLastUsedBucketBits + kLastUsedBucketLowestBit;
58 constexpr int kFirstToastOffsetLowestBit =
59 ExperimentMetrics::kToastHourBits + kToastHourLowestBit;
60 constexpr int kToastCountLowestBit =
61 ExperimentMetrics::kFirstToastOffsetBits + kFirstToastOffsetLowestBit;
62 constexpr int kToastLocationLowestBit =
63 ExperimentMetrics::kToastCountBits + kToastCountLowestBit;
64 constexpr int kStateLowestBit =
65 ExperimentMetrics::kToastLocationBits + kToastLocationLowestBit;
66 constexpr int kGroupLowestBit = ExperimentMetrics::kStateBits + kStateLowestBit;
67 constexpr int kLowestUnusedBit =
68 ExperimentMetrics::kGroupBits + kGroupLowestBit;
69
70 // Helper functions ------------------------------------------------------------
71
72 // Returns the name of the global mutex used to protect the storage location.
73 base::string16 GetMutexName() {
74 base::string16 name(L"Global\\");
75 name.append(install_static::kCompanyPathName);
76 name.append(ShellUtil::GetBrowserModelId(!install_static::IsSystemInstall()));
77 name.append(L"ExperimentStorageMutex");
78 return name;
79 }
80
81 // Populates |path| with the path to the registry key in which the current
82 // user's experiment state is stored. Returns false if the path cannot be
83 // determined.
84 bool GetExperimentStateKeyPath(bool system_level, base::string16* path) {
85 const install_static::InstallDetails& install_details =
86 install_static::InstallDetails::Get();
87
88 if (!system_level) {
89 *path = install_details.GetClientStateKeyPath().append(kRegKeyRetention);
90 return true;
91 }
92
93 base::string16 user_sid;
94 if (base::win::GetUserSidString(&user_sid)) {
95 *path = install_details.GetClientStateMediumKeyPath()
96 .append(kRegKeyRetention)
97 .append(L"\\")
98 .append(user_sid);
99 return true;
100 }
101
102 NOTREACHED();
103 return false;
104 }
105
106 bool OpenParticipationKey(bool write_access, base::win::RegKey* key) {
107 const install_static::InstallDetails& details =
108 install_static::InstallDetails::Get();
109 LONG result = key->Open(
110 details.system_level() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER,
111 details.GetClientStateKeyPath().c_str(),
112 KEY_WOW64_32KEY | (write_access ? KEY_SET_VALUE : KEY_QUERY_VALUE));
113 return result == ERROR_SUCCESS;
114 }
115
116 // Reads |value_name| into |result|. Returns false if the value is not found or
117 // is out of range.
118 template <class T>
119 bool ReadBoundedDWORD(base::win::RegKey* key,
120 const wchar_t* value_name,
121 DWORD min_value,
122 DWORD max_value,
123 T* result) {
124 DWORD dword_value;
125 if (key->ReadValueDW(value_name, &dword_value) != ERROR_SUCCESS)
126 return false;
127 if (dword_value < min_value || dword_value > max_value)
128 return false;
129 *result = static_cast<T>(dword_value);
130 return true;
131 }
132
133 // Reads the internal representation of a Time or TimeDelta from |value_name|
134 // into |result|. Returns false if the value is not found or is out of range.
135 template <class T>
136 bool ReadTime(base::win::RegKey* key, const wchar_t* value_name, T* result) {
137 int64_t qword_value;
138 if (key->ReadInt64(value_name, &qword_value) != ERROR_SUCCESS)
139 return false;
140 *result = T::FromInternalValue(qword_value);
141 return true;
142 }
143
144 void WriteTime(base::win::RegKey* key,
145 const wchar_t* value_name,
146 int64_t internal_time_value) {
147 key->WriteValue(value_name, &internal_time_value, sizeof(internal_time_value),
148 REG_QWORD);
149 }
150
151 } // namespace
152
153 // ExperimentStorage::Lock -----------------------------------------------------
154
155 ExperimentStorage::Lock::~Lock() {
156 BOOL result = ::ReleaseMutex(storage_->mutex_.Get());
157 DCHECK(result);
158 }
159
160 bool ExperimentStorage::Lock::ReadParticipation(Participation* participation) {
161 base::win::RegKey key;
162 // A failure to open the key likely indicates that this isn't running from a
163 // real install of Chrome.
164 if (!OpenParticipationKey(false /* !write_access */, &key))
165 return false;
166
167 DWORD value = 0;
168 LONG result = key.ReadValueDW(kRegValueRetentionStudy, &value);
169 if (result != ERROR_SUCCESS) {
170 // This likely means that the value is not present.
171 *participation = Participation::kNotEvaluated;
172 } else if (value == 0) {
173 *participation = Participation::kNotParticipating;
174 } else {
175 *participation = Participation::kIsParticipating;
176 }
177 return true;
178 }
179
180 bool ExperimentStorage::Lock::WriteParticipation(Participation participation) {
181 base::win::RegKey key;
182 // A failure to open the key likely indicates that this isn't running from a
183 // real install of Chrome.
184 if (!OpenParticipationKey(true /* write_access */, &key))
185 return false;
186
187 if (participation == Participation::kNotEvaluated)
188 return key.DeleteValue(kRegValueRetentionStudy) == ERROR_SUCCESS;
189 const DWORD value = participation == Participation::kIsParticipating ? 1 : 0;
190 return key.WriteValue(kRegValueRetentionStudy, value) == ERROR_SUCCESS;
191 }
192
193 bool ExperimentStorage::Lock::LoadExperiment(Experiment* experiment) {
194 // This function loads both the experiment metrics and state from the
195 // registry.
196 // - If no metrics are found: |experiment| is cleared, and true is returned.
197 // (Per-user experiment data in the registry is ignored for all users.)
198 // - If metrics indicate an initial state (prior to a user being elected into
199 // an experiment group): |experiment| is populated with the metrics and true
200 // is returned. (Per-user experiment data in the registry is ignored for all
201 // users.)
202 // - If metrics indicate an intermediate or terminal state and per-user
203 // experiment data is in the same state: |experiment| is populated with all
204 // data from the registry and true is returned.
205 // Otherwise, the metrics correspond to a different user on the machine, so
206 // false is returned.
207
208 *experiment = Experiment();
209
210 ExperimentMetrics metrics;
211 if (!storage_->LoadMetricsUnsafe(&metrics))
212 return false; // Error reading metrics -- do nothing.
213
214 if (metrics.InInitialState()) {
215 // There should be no per-user experiment data present (ignore it if there
216 // happens to be somehow).
217 experiment->InitializeFromMetrics(metrics);
218 return true;
219 }
220
221 Experiment temp_experiment;
222 if (!storage_->LoadStateUnsafe(&temp_experiment))
223 return false;
224
225 // Verify that the state matches the metrics. Ignore the state if this is not
226 // the case, as the metrics are the source of truth.
227 if (temp_experiment.state() != metrics.state)
228 return false;
229
230 *experiment = temp_experiment;
231 return true;
232 }
233
234 bool ExperimentStorage::Lock::StoreExperiment(const Experiment& experiment) {
235 bool ret = storage_->StoreMetricsUnsafe(experiment.metrics());
236 return storage_->StoreStateUnsafe(experiment) && ret;
237 }
238
239 bool ExperimentStorage::Lock::LoadMetrics(ExperimentMetrics* metrics) {
240 DCHECK_EQ(ExperimentMetrics::kUninitialized, metrics->state);
241 return storage_->LoadMetricsUnsafe(metrics);
242 }
243
244 bool ExperimentStorage::Lock::StoreMetrics(const ExperimentMetrics& metrics) {
245 DCHECK_NE(ExperimentMetrics::kUninitialized, metrics.state);
246 return storage_->StoreMetricsUnsafe(metrics);
247 }
248
249 ExperimentStorage::Lock::Lock(ExperimentStorage* storage) : storage_(storage) {
250 DCHECK(storage);
251 DWORD result = ::WaitForSingleObject(storage_->mutex_.Get(), INFINITE);
252 PLOG_IF(FATAL, result == WAIT_FAILED)
253 << "Failed to lock ExperimentStorage mutex";
254 }
255
256 // ExperimentStorage -----------------------------------------------------------
257
258 ExperimentStorage::ExperimentStorage()
259 : mutex_(::CreateMutex(nullptr, FALSE, GetMutexName().c_str())) {}
260
261 ExperimentStorage::~ExperimentStorage() {}
262
263 std::unique_ptr<ExperimentStorage::Lock> ExperimentStorage::AcquireLock() {
264 return base::WrapUnique(new Lock(this));
265 }
266
267 // static
268 int ExperimentStorage::ReadUint64Bits(uint64_t source,
269 int bit_length,
270 int low_bit) {
271 DCHECK(bit_length > 0 && bit_length <= sizeof(int) * 8 &&
272 low_bit + bit_length <= sizeof(source) * 8);
273 uint64_t bit_mask = (1ULL << bit_length) - 1;
274 return static_cast<int>((source >> low_bit) & bit_mask);
275 }
276
277 // static
278 void ExperimentStorage::SetUint64Bits(int value,
279 int bit_length,
280 int low_bit,
281 uint64_t* target) {
282 DCHECK(bit_length > 0 && bit_length <= sizeof(int) * 8 &&
grt (UTC plus 2) 2017/06/13 12:24:48 sizeof(int) -> sizeof(value)
nikunjb 2017/06/13 21:27:53 Done.
283 low_bit + bit_length <= sizeof(target) * 8);
284 uint64_t bit_mask = (1ULL << bit_length) - 1;
285 *target |= ((static_cast<uint64_t>(value) & bit_mask) << low_bit);
286 }
287
288 bool ExperimentStorage::DecodeMetrics(base::StringPiece16 encoded_metrics,
289 ExperimentMetrics* metrics) {
290 std::string metrics_data;
291
292 if (!base::Base64Decode(base::UTF16ToASCII(encoded_metrics), &metrics_data))
293 return false;
294
295 if (metrics_data.size() != 6)
296 return false;
297
298 uint64_t metrics_value = 0;
299 for (size_t i = 0; i < metrics_data.size(); ++i)
300 SetUint64Bits(metrics_data[i], 8, 8 * i, &metrics_value);
301
302 ExperimentMetrics result;
303 result.session_length_bucket =
304 ReadUint64Bits(metrics_value, ExperimentMetrics::kSessionLengthBucketBits,
305 kSessionLengthBucketLowestBit);
306 result.action_delay_bucket =
307 ReadUint64Bits(metrics_value, ExperimentMetrics::kActionDelayBucketBits,
308 kActionDelayBucketLowestBit);
309 result.last_used_bucket =
310 ReadUint64Bits(metrics_value, ExperimentMetrics::kLastUsedBucketBits,
311 kLastUsedBucketLowestBit);
312 result.toast_hour = ReadUint64Bits(
313 metrics_value, ExperimentMetrics::kToastHourBits, kToastHourLowestBit);
314 result.first_toast_offset_days =
315 ReadUint64Bits(metrics_value, ExperimentMetrics::kFirstToastOffsetBits,
316 kFirstToastOffsetLowestBit);
317 result.toast_count = ReadUint64Bits(
318 metrics_value, ExperimentMetrics::kToastCountBits, kToastCountLowestBit);
319 result.toast_location = static_cast<ExperimentMetrics::ToastLocation>(
320 ReadUint64Bits(metrics_value, ExperimentMetrics::kToastLocationBits,
321 kToastLocationLowestBit));
322
323 static_assert(ExperimentMetrics::State::NUM_STATES <= (1 << 4),
324 "Too many states for ExperimentMetrics encoding.");
325 result.state = static_cast<ExperimentMetrics::State>(ReadUint64Bits(
326 metrics_value, ExperimentMetrics::kStateBits, kStateLowestBit));
327 result.group = ReadUint64Bits(metrics_value, ExperimentMetrics::kGroupBits,
328 kGroupLowestBit);
329
330 if (ReadUint64Bits(metrics_value,
331 sizeof(metrics_value) * 8 - kLowestUnusedBit,
332 kLowestUnusedBit)) {
333 return false;
334 }
335
336 *metrics = result;
337 return true;
338 }
339
340 // static
341 base::string16 ExperimentStorage::EncodeMetrics(
342 const ExperimentMetrics& metrics) {
343 uint64_t metrics_value = 0;
344 SetUint64Bits(metrics.session_length_bucket,
345 ExperimentMetrics::kSessionLengthBucketBits,
346 kSessionLengthBucketLowestBit, &metrics_value);
347 SetUint64Bits(metrics.action_delay_bucket,
348 ExperimentMetrics::kActionDelayBucketBits,
349 kActionDelayBucketLowestBit, &metrics_value);
350 SetUint64Bits(metrics.last_used_bucket,
351 ExperimentMetrics::kLastUsedBucketBits,
352 kLastUsedBucketLowestBit, &metrics_value);
353 SetUint64Bits(metrics.toast_hour, ExperimentMetrics::kToastHourBits,
354 kToastHourLowestBit, &metrics_value);
355 SetUint64Bits(metrics.first_toast_offset_days,
356 ExperimentMetrics::kFirstToastOffsetBits,
357 kFirstToastOffsetLowestBit, &metrics_value);
358 SetUint64Bits(metrics.toast_count, ExperimentMetrics::kToastCountBits,
359 kToastCountLowestBit, &metrics_value);
360 SetUint64Bits(metrics.toast_location, ExperimentMetrics::kToastLocationBits,
361 kToastLocationLowestBit, &metrics_value);
362 static_assert(ExperimentMetrics::State::NUM_STATES <= (1 << 4),
363 "Too many states for ExperimentMetrics encoding.");
364 SetUint64Bits(metrics.state, ExperimentMetrics::kStateBits, kStateLowestBit,
365 &metrics_value);
366 SetUint64Bits(metrics.group, ExperimentMetrics::kGroupBits, kGroupLowestBit,
367 &metrics_value);
368
369 std::string metrics_data(6, '\0');
370 for (size_t i = 0; i < metrics_data.size(); ++i) {
371 metrics_data[i] =
372 static_cast<char>(ReadUint64Bits(metrics_value, 8, 8 * i));
373 }
374 std::string encoded_metrics;
375 base::Base64Encode(metrics_data, &encoded_metrics);
376 return base::ASCIIToUTF16(encoded_metrics);
377 }
378
379 bool ExperimentStorage::LoadMetricsUnsafe(ExperimentMetrics* metrics) {
380 base::string16 value;
381
382 if (!GoogleUpdateSettings::ReadExperimentLabels(
383 install_static::IsSystemInstall(), &value)) {
384 return false;
385 }
386
387 ExperimentLabels experiment_labels(value);
388 base::StringPiece16 encoded_metrics =
389 experiment_labels.GetValueForLabel(kExperimentLabelName);
390 if (encoded_metrics.empty()) {
391 *metrics = ExperimentMetrics();
392 return true;
393 }
394
395 return DecodeMetrics(encoded_metrics, metrics);
396 }
397
398 bool ExperimentStorage::StoreMetricsUnsafe(const ExperimentMetrics& metrics) {
399 base::string16 value;
400 if (!GoogleUpdateSettings::ReadExperimentLabels(
401 install_static::IsSystemInstall(), &value)) {
402 return false;
403 }
404 ExperimentLabels experiment_labels(value);
405
406 experiment_labels.SetValueForLabel(kExperimentLabelName,
407 EncodeMetrics(metrics),
408 base::TimeDelta::FromDays(182));
409
410 return GoogleUpdateSettings::SetExperimentLabels(
411 install_static::IsSystemInstall(), experiment_labels.value());
412 }
413
414 bool ExperimentStorage::LoadStateUnsafe(Experiment* experiment) {
415 const bool system_level = install_static::IsSystemInstall();
416
417 base::string16 path;
418 if (!GetExperimentStateKeyPath(system_level, &path))
419 return false;
420
421 const HKEY root = system_level ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
422 base::win::RegKey key;
423 if (key.Open(root, path.c_str(), KEY_QUERY_VALUE | KEY_WOW64_32KEY) !=
424 ERROR_SUCCESS) {
425 return false;
426 }
427
428 return ReadBoundedDWORD(&key, kRegValueState, 0,
429 ExperimentMetrics::NUM_STATES, &experiment->state_) &&
430 ReadBoundedDWORD(&key, kRegValueGroup, 0,
431 ExperimentMetrics::kNumGroups - 1,
432 &experiment->group_) &&
433 ReadBoundedDWORD(&key, kRegValueToastLocation, 0, 1,
434 &experiment->toast_location_) &&
435 ReadBoundedDWORD(&key, kRegValueInactiveDays, 0, INT_MAX,
436 &experiment->inactive_days_) &&
437 ReadBoundedDWORD(&key, kRegValueToastCount, 0,
438 ExperimentMetrics::kMaxToastCount,
439 &experiment->toast_count_) &&
440 ReadTime(&key, kRegValueFirstDisplayTime,
441 &experiment->first_display_time_) &&
442 ReadTime(&key, kRegValueLatestDisplayTime,
443 &experiment->latest_display_time_) &&
444 ReadTime(&key, kRegValueUserSessionUptime,
445 &experiment->user_session_uptime_) &&
446 ReadTime(&key, kRegValueActionDelay, &experiment->action_delay_);
447 }
448
449 bool ExperimentStorage::StoreStateUnsafe(const Experiment& experiment) {
450 const bool system_level = install_static::IsSystemInstall();
451
452 base::string16 path;
453 if (!GetExperimentStateKeyPath(system_level, &path))
454 return false;
455
456 const HKEY root = system_level ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
457 base::win::RegKey key;
458 if (key.Create(root, path.c_str(), KEY_SET_VALUE | KEY_WOW64_32KEY) !=
459 ERROR_SUCCESS) {
460 return false;
461 }
462
463 key.WriteValue(kRegValueState, experiment.state());
464 key.WriteValue(kRegValueGroup, experiment.group());
465 key.WriteValue(kRegValueToastLocation, experiment.toast_location());
466 key.WriteValue(kRegValueInactiveDays, experiment.inactive_days());
467 key.WriteValue(kRegValueToastCount, experiment.toast_count());
468 WriteTime(&key, kRegValueFirstDisplayTime,
469 experiment.first_display_time().ToInternalValue());
470 WriteTime(&key, kRegValueLatestDisplayTime,
471 experiment.latest_display_time().ToInternalValue());
472 WriteTime(&key, kRegValueUserSessionUptime,
473 experiment.user_session_uptime().ToInternalValue());
474 WriteTime(&key, kRegValueActionDelay,
475 experiment.action_delay().ToInternalValue());
476 return true;
477 }
478
479 } // namespace installer
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698