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

Side by Side Diff: chrome/installer/setup/user_experiment.cc

Issue 2933043002: Installer support for Windows 10 inactive user toast. (Closed)
Patch Set: two studies 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/setup/user_experiment.h"
6
7 #include <windows.h>
8
9 #include <lm.h>
10 #include <shellapi.h>
11 #include <wtsapi32.h>
12
13 #include <memory>
14
15 #include "base/command_line.h"
16 #include "base/files/file_path.h"
17 #include "base/process/launch.h"
18 #include "base/rand_util.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/win/scoped_handle.h"
22 #include "base/win/scoped_process_information.h"
23 #include "base/win/win_util.h"
24 #include "base/win/windows_version.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/install_static/install_modes.h"
27 #include "chrome/install_static/install_util.h"
28 #include "chrome/installer/setup/installer_state.h"
29 #include "chrome/installer/setup/setup_constants.h"
30 #include "chrome/installer/setup/setup_singleton.h"
31 #include "chrome/installer/setup/setup_util.h"
32 #include "chrome/installer/setup/update_active_setup_version_work_item.h"
33 #include "chrome/installer/util/experiment.h"
34 #include "chrome/installer/util/experiment_storage.h"
35 #include "chrome/installer/util/google_update_settings.h"
36 #include "chrome/installer/util/install_util.h"
37 #include "chrome/installer/util/util_constants.h"
38 #include "ui/base/fullscreen_win.h"
39
40 namespace installer {
41
42 namespace {
43
44 // The study currently being conducted.
45 constexpr ExperimentStorage::Study kCurrentStudy = ExperimentStorage::kStudyOne;
46
47 // The primary group for study number two.
48 constexpr int kStudyTwoGroup = 0;
49
50 // Test switches.
51 constexpr char kExperimentEnterpriseBypass[] = "experiment-enterprise-bypass";
52 constexpr char kExperimentParticipation[] = "experiment-participation";
53 constexpr char kExperimentRetryDelay[] = "experiment-retry-delay";
54
55 // Returns true if the install corresponds to an enterprise brand or if the
56 // machine is joined to a domain. This check can be bypassed via
57 // --experiment-enterprise-bypass.
58 bool IsEnterpriseInstall() {
59 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
60 kExperimentEnterpriseBypass)) {
61 return false;
62 }
63 return IsEnterpriseBrand() || IsDomainJoined();
64 }
65
66 // Returns the delay to be used between presentation retries. The default (five
67 // minutes) can be overidden via --experiment-retry-delay=SECONDS.
68 base::TimeDelta GetRetryDelay() {
69 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
70 base::string16 value =
71 command_line->GetSwitchValueNative(kExperimentRetryDelay);
72 int seconds;
73 if (!value.empty() && base::StringToInt(value, &seconds))
74 return base::TimeDelta::FromSeconds(seconds);
75 return base::TimeDelta::FromMinutes(5);
76 }
77
78 // Overrides the participation value for testing if a value is provided via
79 // --experiment-participation=value. "value" may be "one" or "two". Any other
80 // value (or none at all) results in clearing the persisted state for organic
81 // re-evaluation.
82 ExperimentStorage::Study HandleParticipationOverride(
83 ExperimentStorage::Study current_participation,
84 ExperimentStorage::Lock* lock) {
85 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
86 if (!command_line->HasSwitch(kExperimentParticipation))
87 return current_participation;
88
89 base::string16 participation_override =
90 command_line->GetSwitchValueNative(kExperimentParticipation);
91 ExperimentStorage::Study participation = ExperimentStorage::kNoStudySelected;
92 if (participation_override == L"one")
93 participation = ExperimentStorage::kStudyOne;
94 else if (participation_override == L"two")
95 participation = ExperimentStorage::kStudyTwo;
96
97 if (participation != current_participation)
98 lock->WriteParticipation(participation);
99
100 return participation;
101 }
102
103 // This function launches setup as the currently logged-in interactive
104 // user that is the user whose logon session is attached to winsta0\default.
105 // It assumes that currently we are running as SYSTEM in a non-interactive
106 // windowstation.
107 // The function fails if there is no interactive session active, basically
108 // the computer is on but nobody has logged in locally.
109 // Remote Desktop sessions do not count as interactive sessions; running this
110 // method as a user logged in via remote desktop will do nothing.
111 bool LaunchSetupAsConsoleUser(const base::CommandLine& cmd_line) {
112 DWORD console_id = ::WTSGetActiveConsoleSessionId();
113 if (console_id == 0xFFFFFFFF) {
114 PLOG(ERROR) << __func__ << " no session attached to the console";
115 return false;
116 }
117 base::win::ScopedHandle user_token_handle;
118 {
119 HANDLE user_token;
120 if (!::WTSQueryUserToken(console_id, &user_token)) {
121 PLOG(ERROR) << __func__ << " failed to get user token for console_id "
122 << console_id;
123 return false;
124 }
125 user_token_handle.Set(user_token);
126 }
127 base::LaunchOptions options;
128 options.as_user = user_token_handle.Get();
129 options.empty_desktop_name = true;
130 VLOG(1) << "Spawning experiment process: " << cmd_line.GetCommandLineString();
131 if (base::LaunchProcess(cmd_line, options).IsValid())
132 return true;
133 PLOG(ERROR) << "Failed";
134 return false;
135 }
136
137 // Returns true if the Windows shell indicates that the machine isn't in
138 // presentation mode, running a full-screen D3D app, or in a quiet period.
139 bool MayShowNotifications() {
140 QUERY_USER_NOTIFICATION_STATE state = {};
141 HRESULT result = SHQueryUserNotificationState(&state);
142 if (FAILED(result))
143 return true;
144 // Explicitly allow the acceptable states rather than the converse to be sure
145 // there are no surprises should new states be introduced.
146 return state == QUNS_NOT_PRESENT || // Locked/screensaver running.
147 state == QUNS_ACCEPTS_NOTIFICATIONS; // Go for it!
148 }
149
150 bool UserSessionIsNotYoung() {
151 base::Time session_start_time = GetConsoleSessionStartTime();
152 if (session_start_time.is_null())
153 return true;
154
155 base::TimeDelta session_length = base::Time::Now() - session_start_time;
156 return session_length >= base::TimeDelta::FromMinutes(5);
157 }
158
159 bool ActiveWindowIsNotFullscreen() {
160 return !ui::IsFullScreenMode();
161 }
162
163 // Blocks processing if conditions are not right for presentation. Returns true
164 // if presentation should continue, or false otherwise (e.g., another process
165 // requires the setup singleton).
166 bool WaitForPresentation(
167 const SetupSingleton& setup_singleton,
168 Experiment* experiment,
169 ExperimentStorage* storage,
170 std::unique_ptr<ExperimentStorage::Lock>* storage_lock) {
171 base::TimeDelta retry_delay = GetRetryDelay();
172 bool first_sleep = true;
173 bool loop_again = true;
174
175 do {
176 if (MayShowNotifications() && UserSessionIsNotYoung() &&
177 ActiveWindowIsNotFullscreen()) {
178 return true;
179 }
180
181 // Update the state accordingly if this is the first sleep.
182 if (first_sleep) {
183 experiment->SetState(ExperimentMetrics::kDeferringPresentation);
184 (*storage_lock)->StoreExperiment(*experiment);
185 first_sleep = false;
186 }
187
188 // Release the storage lock and wait on the singleton for five minutes.
189 storage_lock->reset();
190 // Break when another process needs the singleton.
191 loop_again = !setup_singleton.WaitForInterrupt(retry_delay);
192 *storage_lock = storage->AcquireLock();
193 } while (loop_again);
194
195 return false;
196 }
197
198 } // namespace
199
200 // Execution may be in the context of the system or a user on it, and no
201 // guarantee is made regarding the setup singleton.
202 bool ShouldRunUserExperiment() {
203 if (!install_static::kUseGoogleUpdateIntegration)
204 return false;
205
206 if (!install_static::SupportsRetentionExperiments())
207 return false;
208
209 // The current experiment only applies to Windows 10 and newer.
210 if (base::win::GetVersion() < base::win::VERSION_WIN10)
211 return false;
212
213 // Enterprise brand codes and domain joined machines are excluded.
214 if (IsEnterpriseInstall())
215 return false;
216
217 // Gain exclusive access to the persistent experiment state. Only per-install
218 // state may be queried (participation and metrics are okay; Experiment itself
219 // is not).
220 ExperimentStorage storage;
221 auto lock = storage.AcquireLock();
222
223 // Bail out if this install is not selected into the fraction participating in
224 // the current study.
225 // NOTE: No clients will participate while this under development.
226 if (true || !IsSelectedForStudy(lock.get(), kCurrentStudy))
227 return false;
228
229 // Skip the experiment if a user on the machine has already reached a terminal
230 // state.
231 ExperimentMetrics metrics;
232 if (!lock->LoadMetrics(&metrics) || metrics.InTerminalState())
233 return false;
234
235 return true;
236 }
237
238 // Execution is from the context of the installer immediately following a
239 // successful update. The setup singleton is held.
240 void BeginUserExperiment(const InstallerState& installer_state,
241 const base::FilePath& setup_path) {
242 ExperimentStorage storage;
243
244 // Prepare a command line to relaunch the installed setup.exe for the
245 // experiment.
246 base::CommandLine setup_command(setup_path);
247 InstallUtil::AppendModeSwitch(&setup_command);
248 if (installer_state.system_install())
249 setup_command.AppendSwitch(switches::kSystemLevel);
250 if (installer_state.verbose_logging())
251 setup_command.AppendSwitch(switches::kVerboseLogging);
252 setup_command.AppendSwitch(switches::kUserExperiment);
253 // Copy any test switches used by the spawned process.
254 static constexpr const char* kSwitchesToCopy[] = {
255 kExperimentRetryDelay,
256 };
257 setup_command.CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(),
258 kSwitchesToCopy, arraysize(kSwitchesToCopy));
259
260 if (!installer_state.system_install()) {
261 VLOG(1) << "Spawning experiment process: "
262 << setup_command.GetCommandLineString();
263 // The installer is already running in the context of an ordinary user.
264 // Relaunch directly to run the experiment.
265 base::LaunchOptions launch_options;
266 launch_options.force_breakaway_from_job_ = true;
267 if (!base::LaunchProcess(setup_command, launch_options).IsValid()) {
268 LOG(ERROR) << __func__
269 << " failed to relaunch installer for user experiment,";
270 WriteInitialState(&storage, ExperimentMetrics::kRelaunchFailed);
271 }
272 return;
273 }
274
275 // The installer is running at high integrity, likely as SYSTEM. Relaunch as
276 // the console user at medium integrity.
277 VLOG(1) << "Attempting to spawn experiment as console user.";
278 if (LaunchSetupAsConsoleUser(setup_command)) {
279 return;
280 }
281
282 // Trigger Active Setup to run on the next user logon if this machine has
283 // never participated in the experiment. This will be done at most once per
284 // machine, even across updates. Doing so more often risks having excessive
285 // active setup activity for some users.
286 auto storage_lock = storage.AcquireLock();
287 ExperimentMetrics experiment_metrics;
288 if (storage_lock->LoadMetrics(&experiment_metrics) &&
289 experiment_metrics.state == ExperimentMetrics::kUninitialized) {
290 UpdateActiveSetupVersionWorkItem item(
291 install_static::GetActiveSetupPath(),
292 UpdateActiveSetupVersionWorkItem::UPDATE_AND_BUMP_SELECTIVE_TRIGGER);
293 if (item.Do()) {
294 VLOG(1) << "Bumped Active Setup Version for user experiment";
295 experiment_metrics.state = ExperimentMetrics::kWaitingForUserLogon;
296 storage_lock->StoreMetrics(experiment_metrics);
297 } else {
298 LOG(ERROR) << "Failed to bump Active Setup Version for user experiment.";
299 }
300 }
301 }
302
303 // This function executes within the context of a signed-in user, even for the
304 // case of system-level installs. In particular, it may be run in a spawned
305 // setup.exe immediately after a successful update or following user logon as a
306 // result of Active Setup.
307 void RunUserExperiment(const base::CommandLine& command_line,
308 const MasterPreferences& master_preferences,
309 InstallationState* original_state,
310 InstallerState* installer_state) {
311 VLOG(1) << __func__;
312
313 ExperimentStorage storage;
314 WriteInitialState(&storage, ExperimentMetrics::kWaitingForSingleton);
315 std::unique_ptr<SetupSingleton> setup_singleton(SetupSingleton::Acquire(
316 command_line, master_preferences, original_state, installer_state));
317 if (!setup_singleton) {
318 VLOG(1) << "Timed out while waiting for setup singleton";
319 WriteInitialState(&storage, ExperimentMetrics::kSingletonWaitTimeout);
320 return;
321 }
322
323 Experiment experiment;
324 auto storage_lock = storage.AcquireLock();
325
326 // Determine the study in which this client participates.
327 ExperimentStorage::Study participation = ExperimentStorage::kNoStudySelected;
328 if (!storage_lock->ReadParticipation(&participation) ||
329 participation == ExperimentStorage::kNoStudySelected) {
330 // ShouldRunUserExperiment should have brought this client into a particular
331 // study. Something is very wrong if it can't be determined here.
332 LOG(ERROR) << "Failed to read study participation.";
333 return;
334 }
335
336 if (!storage_lock->LoadExperiment(&experiment)) {
337 // The metrics correspond to a different user on the machine; nothing to do.
338 VLOG(1) << "Another user is participating in the experiment.";
339 return;
340 }
341
342 // There is nothing to do if the user has already reached a terminal state.
343 if (experiment.metrics().InTerminalState()) {
344 VLOG(1) << "Experiment has reached terminal state: "
345 << experiment.metrics().state;
346 return;
347 }
348
349 // Now the fun begins. Assign this user to a group if this is the first time
350 // through.
351 if (experiment.metrics().InInitialState()) {
352 experiment.AssignGroup(PickGroup(participation));
353 VLOG(1) << "Assigned user to experiment group: "
354 << experiment.metrics().group;
355 }
356
357 // Chrome is considered actively used if it has been run within the last 28
358 // days or if it was installed within the same time period.
359 int days_ago_last_run = GoogleUpdateSettings::GetLastRunTime();
360 if ((days_ago_last_run >= 0 ? days_ago_last_run
361 : GetInstallAge(*installer_state)) <= 28) {
362 VLOG(1) << "Aborting experiment due to activity.";
363 experiment.SetState(ExperimentMetrics::kIsActive);
364 storage_lock->StoreExperiment(experiment);
365 return;
366 }
367
368 // Check for a dormant user: one for which the machine has been off or the
369 // user has been signed out for more than 90% of the last 28 days.
370 if (false) { // TODO(grt): Implement this.
371 VLOG(1) << "Aborting experiment due to dormancy.";
372 experiment.SetState(ExperimentMetrics::kIsDormant);
373 storage_lock->StoreExperiment(experiment);
374 return;
375 }
376
377 if (base::win::IsTabletDevice(nullptr)) {
378 VLOG(1) << "Aborting experiment due to tablet device.";
379 experiment.SetState(ExperimentMetrics::kIsTabletDevice);
380 storage_lock->StoreExperiment(experiment);
381 return;
382 }
383
384 if (!WaitForPresentation(*setup_singleton, &experiment, &storage,
385 &storage_lock)) {
386 VLOG(1) << "Aborting experiment while waiting to present.";
387 experiment.SetState(ExperimentMetrics::kDeferredPresentationAborted);
388 storage_lock->StoreExperiment(experiment);
389 return;
390 }
391
392 VLOG(1) << "Launching Chrome to show the toast.";
393 experiment.SetState(ExperimentMetrics::kLaunchingChrome);
394 storage_lock->StoreExperiment(experiment);
395 LaunchChrome(*installer_state, experiment);
396 }
397
398 // Writes the initial state |state| to the registry if there is no existing
399 // state for this or another user.
400 void WriteInitialState(ExperimentStorage* storage,
401 ExperimentMetrics::State state) {
402 auto storage_lock = storage->AcquireLock();
403
404 // Write the state provided that there is either no existing state or that
405 // any that exists also represents an initial state.
406 ExperimentMetrics experiment_metrics;
407 if (storage_lock->LoadMetrics(&experiment_metrics) &&
408 experiment_metrics.InInitialState()) {
409 experiment_metrics.state = state;
410 storage_lock->StoreMetrics(experiment_metrics);
411 }
412 }
413
414 bool IsEnterpriseBrand() {
415 base::string16 brand;
416
417 if (!GoogleUpdateSettings::GetBrand(&brand))
418 return false;
419
420 if (brand.length() != 4)
421 return false;
422
423 if (brand == L"GGRV")
Patrick Monette 2017/06/13 19:13:40 NIt: Is there any comment or link that could be ad
grt (UTC plus 2) 2017/06/14 20:43:44 +georgesak to confirm that I have the correct set
Georges Khalil 2017/06/15 14:43:48 These are the correct codes indeed. But I think i
grt (UTC plus 2) 2017/06/15 15:07:26 Hmm. Yeah, I can do that. Thanks for the suggestio
424 return true;
425
426 return brand[0] == L'G' && brand[1] == L'C' && brand[2] == L'E' &&
427 brand[3] != L'L' && brand[3] >= L'A' && brand[3] <= L'U';
428 }
429
430 bool IsDomainJoined() {
431 LPWSTR buffer = nullptr;
432 NETSETUP_JOIN_STATUS buffer_type = NetSetupUnknownStatus;
433 bool is_joined =
434 ::NetGetJoinInformation(nullptr, &buffer, &buffer_type) == NERR_Success &&
435 buffer_type == NetSetupDomainName;
436 if (buffer)
437 NetApiBufferFree(buffer);
438
439 return is_joined;
440 }
441
442 bool IsSelectedForStudy(ExperimentStorage::Lock* lock,
443 ExperimentStorage::Study current_study) {
444 ExperimentStorage::Study participation = ExperimentStorage::kNoStudySelected;
445 if (!lock->ReadParticipation(&participation))
446 return false;
447
448 participation = HandleParticipationOverride(participation, lock);
449
450 if (participation == ExperimentStorage::kNoStudySelected) {
451 // This install has not been evaluated for participation. Do so now. Select
452 // a small population into the first study of the experiment. Everyone else
453 // gets the second study.
454 participation = base::RandDouble() <= 0.02756962532
455 ? ExperimentStorage::kStudyOne
456 : ExperimentStorage::kStudyTwo;
457 if (!lock->WriteParticipation(participation))
458 return false;
459 }
460
461 return participation <= current_study;
462 }
463
464 int PickGroup(ExperimentStorage::Study participation) {
465 DCHECK(participation == ExperimentStorage::kStudyOne ||
466 participation == ExperimentStorage::kStudyTwo);
467 static constexpr int kHoldbackGroup = ExperimentMetrics::kNumGroups - 1;
468
469 if (participation == ExperimentStorage::kStudyOne) {
470 // Evenly distrubute clients among the groups.
471 return base::RandInt(0, ExperimentMetrics::kNumGroups - 1);
472 }
473
474 // 1% holdback, 99% in the winning group.
475 return base::RandDouble() < 0.01 ? kHoldbackGroup : kStudyTwoGroup;
476 }
477
478 void LaunchChrome(const InstallerState& installer_state,
479 const Experiment& experiment) {
480 const base::FilePath chrome_exe =
481 installer_state.target_path().Append(kChromeExe);
482 base::CommandLine command_line(chrome_exe);
483 command_line.AppendSwitchNative(::switches::kTryChromeAgain,
484 base::IntToString16(experiment.group()));
485
486 STARTUPINFOW startup_info = {sizeof(startup_info)};
487 PROCESS_INFORMATION temp_process_info = {};
488 base::string16 writable_command_line_string(
489 command_line.GetCommandLineString());
490 if (!::CreateProcess(
491 chrome_exe.value().c_str(), &writable_command_line_string[0],
492 nullptr /* lpProcessAttributes */, nullptr /* lpThreadAttributes */,
493 FALSE /* bInheritHandles */, CREATE_NO_WINDOW,
494 nullptr /* lpEnvironment */, nullptr /* lpCurrentDirectory */,
495 &startup_info, &temp_process_info)) {
496 PLOG(ERROR) << "Failed to launch: " << writable_command_line_string;
497 return;
498 }
499
500 base::win::ScopedProcessInformation process_info(temp_process_info);
501 }
502
503 } // namespace installer
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698