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 "chrome/browser/sync/startup_controller.h"
7 #include "base/command_line.h"
8 #include "base/message_loop/message_loop.h"
9 #include "base/metrics/histogram.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
12 #include "chrome/common/chrome_switches.h"
13 #include "components/signin/core/browser/profile_oauth2_token_service.h"
14 #include "components/sync_driver/sync_prefs.h"
16 namespace browser_sync
{
20 // The amount of time we'll wait to initialize sync if no data type triggers
21 // initialization via a StartSyncFlare.
22 const int kDeferredInitFallbackSeconds
= 10;
24 // Enum (for UMA, primarily) defining different events that cause us to
25 // exit the "deferred" state of initialization and invoke start_backend.
26 enum DeferredInitTrigger
{
27 // We have received a signal from a SyncableService requesting that sync
28 // starts as soon as possible.
29 TRIGGER_DATA_TYPE_REQUEST
,
30 // No data type requested sync to start and our fallback timer expired.
31 TRIGGER_FALLBACK_TIMER
,
37 StartupController::StartupController(
38 ProfileSyncServiceStartBehavior start_behavior
,
39 const ProfileOAuth2TokenService
* token_service
,
40 const sync_driver::SyncPrefs
* sync_prefs
,
41 const SupervisedUserSigninManagerWrapper
* signin
,
42 base::Closure start_backend
)
43 : received_start_request_(false),
44 setup_in_progress_(false),
45 auto_start_enabled_(start_behavior
== AUTO_START
),
46 sync_prefs_(sync_prefs
),
47 token_service_(token_service
),
49 start_backend_(start_backend
),
51 base::TimeDelta::FromSeconds(kDeferredInitFallbackSeconds
)),
54 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
55 switches::kSyncDeferredStartupTimeoutSeconds
)) {
56 int timeout
= kDeferredInitFallbackSeconds
;
57 if (base::StringToInt(
58 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
59 switches::kSyncDeferredStartupTimeoutSeconds
),
61 DCHECK_GE(timeout
, 0);
62 DVLOG(2) << "Sync StartupController overriding startup timeout to "
63 << timeout
<< " seconds.";
64 fallback_timeout_
= base::TimeDelta::FromSeconds(timeout
);
69 StartupController::~StartupController() {}
71 void StartupController::Reset(const syncer::ModelTypeSet registered_types
) {
72 received_start_request_
= false;
73 start_up_time_
= base::Time();
74 start_backend_time_
= base::Time();
75 // Don't let previous timers affect us post-reset.
76 weak_factory_
.InvalidateWeakPtrs();
77 registered_types_
= registered_types
;
80 void StartupController::set_setup_in_progress(bool in_progress
) {
81 setup_in_progress_
= in_progress
;
84 bool StartupController::StartUp(StartUpDeferredOption deferred_option
) {
85 const bool first_start
= start_up_time_
.is_null();
87 start_up_time_
= base::Time::Now();
89 if (deferred_option
== STARTUP_BACKEND_DEFERRED
&&
90 !base::CommandLine::ForCurrentProcess()->HasSwitch(
91 switches::kSyncDisableDeferredStartup
) &&
92 sync_prefs_
->GetPreferredDataTypes(registered_types_
)
93 .Has(syncer::SESSIONS
)) {
95 base::MessageLoop::current()->PostDelayedTask(
97 base::Bind(&StartupController::OnFallbackStartupTimerExpired
,
98 weak_factory_
.GetWeakPtr()), fallback_timeout_
);
103 if (start_backend_time_
.is_null()) {
104 start_backend_time_
= base::Time::Now();
105 start_backend_
.Run();
106 first_start_
= false;
112 void StartupController::OverrideFallbackTimeoutForTest(
113 const base::TimeDelta
& timeout
) {
114 fallback_timeout_
= timeout
;
117 bool StartupController::TryStart() {
118 if (sync_prefs_
->IsManaged())
121 if (sync_prefs_
->IsStartSuppressed())
124 if (signin_
->GetEffectiveUsername().empty())
130 if (!token_service_
->RefreshTokenIsAvailable(
131 signin_
->GetAccountIdToUse())) {
135 // TODO(tim): Seems wrong to always record this histogram here...
136 // If we got here then tokens are loaded and user logged in and sync is
137 // enabled. If OAuth refresh token is not available then something is wrong.
138 // When PSS requests access token, OAuth2TokenService will return error and
139 // PSS will show error to user asking to reauthenticate.
140 UMA_HISTOGRAM_BOOLEAN("Sync.RefreshTokenAvailable", true);
142 // If sync setup has completed we always start the backend. If the user is in
143 // the process of setting up now, we should start the backend to download
144 // account control state / encryption information). If autostart is enabled,
145 // but we haven't completed sync setup, we try to start sync anyway, since
146 // it's possible we crashed/shutdown after logging in but before the backend
147 // finished initializing the last time.
149 // However, the only time we actually need to start sync _immediately_ is if
150 // we haven't completed sync setup and the user is in the process of setting
151 // up - either they just signed in (for the first time) on an auto-start
152 // platform or they explicitly kicked off sync setup, and e.g we need to
153 // fetch account details like encryption state to populate UI. Otherwise,
154 // for performance reasons and maximizing parallelism at chrome startup, we
155 // defer the heavy lifting for sync init until things have calmed down.
156 if (sync_prefs_
->HasSyncSetupCompleted()) {
157 // For first time, defer start if data type hasn't requested sync to avoid
158 // stressing browser start. If |first_start_| is false, most likely the
159 // first attempt to start is intercepted by backup. When backup finishes,
160 // TryStart() is called again and we should start immediately to avoid
161 // unnecessary delay.
162 if (!received_start_request_
&& first_start_
)
163 return StartUp(STARTUP_BACKEND_DEFERRED
);
165 return StartUp(STARTUP_IMMEDIATE
);
166 } else if (setup_in_progress_
|| auto_start_enabled_
) {
167 // We haven't completed sync setup. Start immediately if the user explicitly
168 // kicked this off or we're supposed to automatically start syncing.
169 return StartUp(STARTUP_IMMEDIATE
);
175 void StartupController::RecordTimeDeferred() {
176 DCHECK(!start_up_time_
.is_null());
177 base::TimeDelta time_deferred
= base::Time::Now() - start_up_time_
;
178 UMA_HISTOGRAM_CUSTOM_TIMES("Sync.Startup.TimeDeferred2",
180 base::TimeDelta::FromSeconds(0),
181 base::TimeDelta::FromMinutes(2),
185 void StartupController::OnFallbackStartupTimerExpired() {
186 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
187 switches::kSyncDisableDeferredStartup
));
189 if (!start_backend_time_
.is_null())
192 DVLOG(2) << "Sync deferred init fallback timer expired, starting backend.";
193 RecordTimeDeferred();
194 UMA_HISTOGRAM_ENUMERATION("Sync.Startup.DeferredInitTrigger",
195 TRIGGER_FALLBACK_TIMER
,
197 received_start_request_
= true;
201 std::string
StartupController::GetBackendInitializationStateString() const {
202 if (!start_backend_time_
.is_null())
204 else if (!start_up_time_
.is_null())
207 return "Not started";
210 void StartupController::OnDataTypeRequestsSyncStartup(syncer::ModelType type
) {
211 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
212 switches::kSyncDisableDeferredStartup
)) {
213 DVLOG(2) << "Ignoring data type request for sync startup: "
214 << syncer::ModelTypeToString(type
);
218 if (!start_backend_time_
.is_null())
221 DVLOG(2) << "Data type requesting sync startup: "
222 << syncer::ModelTypeToString(type
);
223 // Measure the time spent waiting for init and the type that triggered it.
224 // We could measure the time spent deferred on a per-datatype basis, but
225 // for now this is probably sufficient.
226 if (!start_up_time_
.is_null()) {
227 RecordTimeDeferred();
228 UMA_HISTOGRAM_ENUMERATION("Sync.Startup.TypeTriggeringInit",
229 ModelTypeToHistogramInt(type
),
230 syncer::MODEL_TYPE_COUNT
);
231 UMA_HISTOGRAM_ENUMERATION("Sync.Startup.DeferredInitTrigger",
232 TRIGGER_DATA_TYPE_REQUEST
,
235 received_start_request_
= true;
239 } // namespace browser_sync