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

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

Powered by Google App Engine
This is Rietveld 408576698