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

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);
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())
140 return false;
141 *result = T::FromInternalValue(static_cast<int64_t>(qword_value));
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 metrics.state != ExperimentMetrics::kUninitialized) {
grt (UTC plus 2) 2017/06/08 11:06:23 I this this addition is incorrect. LoadMetricsUnsa
nikunjb 2017/06/09 02:16:31 Okay. Thanks for catching. Modified it. The reas
217 // There should be no per-user experiment data present (ignore it if there
218 // happens to be somehow).
219 experiment->InitializeFromMetrics(metrics);
220 return true;
221 }
222
223 Experiment temp_experiment;
224 if (!storage_->LoadStateUnsafe(&temp_experiment))
225 return false;
226
227 // Verify that the state matches the metrics. Ignore the state if this is not
228 // the case, as the metrics are the source of truth.
229 if (temp_experiment.state_ != metrics.state)
230 return false;
231
232 *experiment = temp_experiment;
233 return true;
234 }
235
236 bool ExperimentStorage::Lock::StoreExperiment(const Experiment& experiment) {
237 bool ret = storage_->StoreMetricsUnsafe(experiment.metrics());
238 return storage_->StoreStateUnsafe(experiment) && ret;
239 }
240
241 bool ExperimentStorage::Lock::LoadMetrics(ExperimentMetrics* metrics) {
242 DCHECK_EQ(ExperimentMetrics::kUninitialized, metrics->state);
243 return storage_->LoadMetricsUnsafe(metrics);
244 }
245
246 bool ExperimentStorage::Lock::StoreMetrics(const ExperimentMetrics& metrics) {
247 DCHECK_NE(ExperimentMetrics::kUninitialized, metrics.state);
248 return storage_->StoreMetricsUnsafe(metrics);
249 }
250
251 ExperimentStorage::Lock::Lock(ExperimentStorage* storage) : storage_(storage) {
252 DCHECK(storage);
253 DWORD result = ::WaitForSingleObject(storage_->mutex_.Get(), INFINITE);
254 PLOG_IF(FATAL, result == WAIT_FAILED)
255 << "Failed to lock ExperimentStorage mutex";
256 }
257
258 // ExperimentStorage -----------------------------------------------------------
259
260 ExperimentStorage::ExperimentStorage()
261 : mutex_(::CreateMutex(nullptr, FALSE, GetMutexName().c_str())) {}
262
263 ExperimentStorage::~ExperimentStorage() {}
264
265 std::unique_ptr<ExperimentStorage::Lock> ExperimentStorage::AcquireLock() {
266 return base::WrapUnique(new Lock(this));
267 }
268
269 // static
270 int ExperimentStorage::ReadUint64Bits(uint64_t source, int len, int low_bit) {
271 DCHECK(len > 0 && len <= 32 && low_bit + len <= 64);
272 uint64_t bit_mask = (uint64_t(1) << len) - 1;
273 return static_cast<int>((source >> low_bit) & bit_mask);
274 }
275
276 // static
277 void ExperimentStorage::SetUint64Bits(int value,
278 int len,
279 int low_bit,
280 uint64_t* source) {
281 DCHECK(len > 0 && len <= 32);
282 uint64_t bit_mask = (uint64_t(1) << len) - 1;
283 *source |= ((uint64_t(value) & bit_mask) << low_bit);
284 }
285
286 bool ExperimentStorage::DecodeMetrics(base::StringPiece16 encoded_metrics,
287 ExperimentMetrics* metrics) {
288 std::string metrics_data;
289
290 if (!base::Base64Decode(base::UTF16ToASCII(encoded_metrics), &metrics_data))
291 return false;
292
293 if (metrics_data.size() != 6)
294 return false;
295
296 uint64_t metrics_value = 0;
297 for (size_t i = 0; i < metrics_data.size(); ++i) {
298 SetUint64Bits(metrics_data[i], 8, 8 * i, &metrics_value);
299 }
300
301 ExperimentMetrics result;
302 result.session_length_bucket =
303 ReadUint64Bits(metrics_value, ExperimentMetrics::kSessionLengthBucketBits,
304 kSessionLengthBucketLowestBit);
305 result.action_delay_bucket =
306 ReadUint64Bits(metrics_value, ExperimentMetrics::kActionDelayBucketBits,
307 kActionDelayBucketLowestBit);
308 result.last_used_bucket =
309 ReadUint64Bits(metrics_value, ExperimentMetrics::kLastUsedBucketBits,
310 kLastUsedBucketLowestBit);
311 result.toast_hour = ReadUint64Bits(
312 metrics_value, ExperimentMetrics::kToastHourBits, kToastHourLowestBit);
313 result.first_toast_offset =
314 ReadUint64Bits(metrics_value, ExperimentMetrics::kFirstToastOffsetBits,
315 kFirstToastOffsetLowestBit);
316 result.toast_count = ReadUint64Bits(
317 metrics_value, ExperimentMetrics::kToastCountBits, kToastCountLowestBit);
318 result.toast_location = static_cast<ExperimentMetrics::ToastLocation>(
319 ReadUint64Bits(metrics_value, ExperimentMetrics::kToastLocationBits,
320 kToastLocationLowestBit));
321
322 static_assert(ExperimentMetrics::State::NUM_STATES <= (1 << 4),
323 "Too many states for ExperimentMetrics encoding.");
324 result.state = static_cast<ExperimentMetrics::State>(ReadUint64Bits(
325 metrics_value, ExperimentMetrics::kStateBits, kStateLowestBit));
326 result.group = ReadUint64Bits(metrics_value, ExperimentMetrics::kGroupBits,
327 kGroupLowestBit);
328
329 int lowest_unused_bit = ExperimentMetrics::kGroupBits + kGroupLowestBit;
330 if (ReadUint64Bits(metrics_value, 64 - lowest_unused_bit,
331 lowest_unused_bit) != 0)
332 return false;
333
334 *metrics = result;
335 return true;
336 }
337
338 // static
339 base::string16 ExperimentStorage::EncodeMetrics(
340 const ExperimentMetrics& metrics) {
341 uint64_t metrics_value = 0;
342 SetUint64Bits(metrics.session_length_bucket,
343 ExperimentMetrics::kSessionLengthBucketBits,
344 kSessionLengthBucketLowestBit, &metrics_value);
345 SetUint64Bits(metrics.action_delay_bucket,
346 ExperimentMetrics::kActionDelayBucketBits,
347 kActionDelayBucketLowestBit, &metrics_value);
348 SetUint64Bits(metrics.last_used_bucket,
349 ExperimentMetrics::kLastUsedBucketBits,
350 kLastUsedBucketLowestBit, &metrics_value);
351 SetUint64Bits(metrics.toast_hour, ExperimentMetrics::kToastHourBits,
352 kToastHourLowestBit, &metrics_value);
353 SetUint64Bits(metrics.first_toast_offset,
354 ExperimentMetrics::kFirstToastOffsetBits,
355 kFirstToastOffsetLowestBit, &metrics_value);
356 SetUint64Bits(metrics.toast_count, ExperimentMetrics::kToastCountBits,
357 kToastCountLowestBit, &metrics_value);
358 SetUint64Bits(metrics.toast_location, ExperimentMetrics::kToastLocationBits,
359 kToastLocationLowestBit, &metrics_value);
360 static_assert(ExperimentMetrics::State::NUM_STATES <= (1 << 4),
361 "Too many states for ExperimentMetrics encoding.");
362 SetUint64Bits(metrics.state, ExperimentMetrics::kStateBits, kStateLowestBit,
363 &metrics_value);
364 SetUint64Bits(metrics.group, ExperimentMetrics::kGroupBits, kGroupLowestBit,
365 &metrics_value);
366
367 std::string metrics_data(6, '\0');
368 for (size_t i = 0; i < metrics_data.size(); ++i) {
369 metrics_data[i] =
370 static_cast<char>(ReadUint64Bits(metrics_value, 8, 8 * i));
371 }
372 std::string encoded_metrics;
373 base::Base64Encode(metrics_data, &encoded_metrics);
374 return base::ASCIIToUTF16(encoded_metrics);
375 }
376
377 bool ExperimentStorage::LoadMetricsUnsafe(ExperimentMetrics* metrics) {
378 base::string16 value;
379
380 if (!GoogleUpdateSettings::ReadExperimentLabels(
381 install_static::IsSystemInstall(), &value)) {
382 return false;
383 }
384
385 ExperimentLabels experiment_labels(value);
386 base::StringPiece16 encoded_metrics =
387 experiment_labels.GetValueForLabel(kExperimentLabelName);
388 if (encoded_metrics.empty()) {
389 *metrics = ExperimentMetrics();
390 return true;
391 }
392
393 return DecodeMetrics(encoded_metrics, metrics);
394 }
395
396 bool ExperimentStorage::StoreMetricsUnsafe(const ExperimentMetrics& metrics) {
397 base::string16 value;
398 if (!GoogleUpdateSettings::ReadExperimentLabels(
399 install_static::IsSystemInstall(), &value)) {
400 return false;
401 }
402 ExperimentLabels experiment_labels(value);
403
404 experiment_labels.SetValueForLabel(kExperimentLabelName,
405 EncodeMetrics(metrics),
406 base::TimeDelta::FromDays(182));
407
408 return GoogleUpdateSettings::SetExperimentLabels(
409 install_static::IsSystemInstall(), experiment_labels.value());
410 // TODO(grt): Update the "client" value here if needed and if possible.
411 // Updates must take place at high integrity, or via a registry handle
412 // provided by a high integrity caller.
413 }
414
415 bool ExperimentStorage::LoadStateUnsafe(Experiment* experiment) {
416 const bool system_level = install_static::IsSystemInstall();
417
418 base::string16 path;
419 if (!GetExperimentStateKeyPath(system_level, &path))
420 return false;
421
422 const HKEY root = system_level ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
423 base::win::RegKey key;
424 if (key.Open(root, path.c_str(), KEY_QUERY_VALUE | KEY_WOW64_32KEY) !=
425 ERROR_SUCCESS) {
426 return false;
427 }
428
429 return ReadBoundedDWORD(&key, kRegValueState, 0,
430 ExperimentMetrics::NUM_STATES, &experiment->state_) &&
431 ReadBoundedDWORD(&key, kRegValueGroup, 0,
432 ExperimentMetrics::kNumGroups - 1,
433 &experiment->group_) &&
434 ReadBoundedDWORD(&key, kRegValueToastLocation, 0, 1,
435 &experiment->toast_location_) &&
436 ReadBoundedDWORD(&key, kRegValueInactiveDays, 0, INT_MAX,
437 &experiment->inactive_days_) &&
438 ReadBoundedDWORD(&key, kRegValueToastCount, 0,
439 ExperimentMetrics::kMaxToastCount,
440 &experiment->toast_count_) &&
441 ReadTime(&key, kRegValueFirstDisplayTime,
442 &experiment->first_display_time_) &&
443 ReadTime(&key, kRegValueLatestDisplayTime,
444 &experiment->latest_display_time_) &&
445 ReadTime(&key, kRegValueUserSessionUptime,
446 &experiment->user_session_uptime_) &&
447 ReadTime(&key, kRegValueActionDelay, &experiment->action_delay_);
448 }
449
450 bool ExperimentStorage::StoreStateUnsafe(const Experiment& experiment) {
451 const bool system_level = install_static::IsSystemInstall();
452
453 base::string16 path;
454 if (!GetExperimentStateKeyPath(system_level, &path))
455 return false;
456
457 const HKEY root = system_level ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
458 base::win::RegKey key;
459 if (key.Create(root, path.c_str(), KEY_SET_VALUE | KEY_WOW64_32KEY) !=
460 ERROR_SUCCESS) {
461 return false;
462 }
463
464 key.WriteValue(kRegValueState, experiment.state_);
465 key.WriteValue(kRegValueGroup, experiment.group_);
466 key.WriteValue(kRegValueToastLocation, experiment.toast_location_);
467 key.WriteValue(kRegValueInactiveDays, experiment.inactive_days_);
468 key.WriteValue(kRegValueToastCount, experiment.toast_count_);
469 WriteTime(&key, kRegValueFirstDisplayTime,
470 experiment.first_display_time_.ToInternalValue());
471 WriteTime(&key, kRegValueLatestDisplayTime,
472 experiment.latest_display_time_.ToInternalValue());
473 WriteTime(&key, kRegValueUserSessionUptime,
474 experiment.user_session_uptime_.ToInternalValue());
475 WriteTime(&key, kRegValueActionDelay,
476 experiment.action_delay_.ToInternalValue());
477 return true;
478 }
479
480 } // namespace installer
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698