1 // Copyright (c) 2012 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/glue/non_ui_data_type_controller.h"
7 #include "base/logging.h"
8 #include "base/memory/weak_ptr.h"
9 #include "chrome/browser/profiles/profile.h"
10 #include "chrome/browser/sync/glue/shared_change_processor_ref.h"
11 #include "chrome/browser/sync/profile_sync_components_factory.h"
12 #include "chrome/browser/sync/profile_sync_service.h"
13 #include "content/public/browser/browser_thread.h"
14 #include "sync/api/sync_error.h"
15 #include "sync/api/syncable_service.h"
16 #include "sync/internal_api/public/base/model_type.h"
17 #include "sync/util/data_type_histogram.h"
19 using content::BrowserThread;
21 namespace browser_sync {
23 NonUIDataTypeController::NonUIDataTypeController(
24 ProfileSyncComponentsFactory* profile_sync_factory,
26 ProfileSyncService* sync_service)
27 : profile_sync_factory_(profile_sync_factory),
29 sync_service_(sync_service),
33 void NonUIDataTypeController::LoadModels(
34 const ModelLoadCallback& model_load_callback) {
35 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
36 DCHECK(!model_load_callback.is_null());
37 if (state() != NOT_RUNNING) {
38 model_load_callback.Run(type(),
39 syncer::SyncError(FROM_HERE,
40 syncer::SyncError::DATATYPE_ERROR,
41 "Model already running",
46 state_ = MODEL_STARTING;
48 // Since we can't be called multiple times before Stop() is called,
49 // |shared_change_processor_| must be NULL here.
50 DCHECK(!shared_change_processor_.get());
51 shared_change_processor_ =
52 profile_sync_factory_->CreateSharedChangeProcessor();
53 DCHECK(shared_change_processor_.get());
55 model_load_callback_ = model_load_callback;
57 // If we are waiting for some external service to load before associating
58 // or we failed to start the models, we exit early.
59 DCHECK(state() == MODEL_STARTING || state() == NOT_RUNNING);
66 void NonUIDataTypeController::OnModelLoaded() {
67 DCHECK_EQ(state_, MODEL_STARTING);
68 DCHECK(!model_load_callback_.is_null());
69 state_ = MODEL_LOADED;
71 ModelLoadCallback model_load_callback = model_load_callback_;
72 model_load_callback_.Reset();
73 model_load_callback.Run(type(), syncer::SyncError());
76 bool NonUIDataTypeController::StartModels() {
77 DCHECK_EQ(state_, MODEL_STARTING);
78 // By default, no additional services need to be started before we can proceed
79 // with model association.
83 void NonUIDataTypeController::StopModels() {
84 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
87 void NonUIDataTypeController::StartAssociating(
88 const StartCallback& start_callback) {
89 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
90 DCHECK(!start_callback.is_null());
91 DCHECK_EQ(state_, MODEL_LOADED);
94 start_callback_ = start_callback;
95 if (!StartAssociationAsync()) {
96 syncer::SyncError error(
98 syncer::SyncError::DATATYPE_ERROR,
99 "Failed to post StartAssociation",
101 syncer::SyncMergeResult local_merge_result(type());
102 local_merge_result.set_error(error);
103 StartDoneImpl(ASSOCIATION_FAILED,
106 syncer::SyncMergeResult(type()));
107 // StartDoneImpl should have called ClearSharedChangeProcessor();
108 DCHECK(!shared_change_processor_.get());
113 void NonUIDataTypeController::Stop() {
114 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
115 if (state() == NOT_RUNNING) {
116 // Stop() should never be called for datatypes that are already stopped.
121 // Disconnect the change processor. At this point, the
122 // syncer::SyncableService can no longer interact with the Syncer, even if
123 // it hasn't finished MergeDataAndStartSyncing.
124 ClearSharedChangeProcessor();
126 // If we haven't finished starting, we need to abort the start.
131 return; // The datatype was never activated, we're done.
134 StartDoneImpl(ABORTED,
136 syncer::SyncMergeResult(type()),
137 syncer::SyncMergeResult(type()));
138 // We continue on to deactivate the datatype and stop the local service.
142 // If DTC is loaded or disabled, we never attempted or succeeded
143 // associating and never activated the datatype. We would have already
144 // stopped the local service in StartDoneImpl(..).
145 state_ = NOT_RUNNING;
149 // Datatype was fully started. Need to deactivate and stop the local
151 DCHECK_EQ(state(), RUNNING);
157 // Deactivate the DataType on the UI thread. We dont want to listen
158 // for any more changes or process them from the server.
159 sync_service_->DeactivateDataType(type());
161 // Stop the local service and release our references to it and the
162 // shared change processor (posts a task to the datatype's thread).
163 StopLocalServiceAsync();
165 state_ = NOT_RUNNING;
168 std::string NonUIDataTypeController::name() const {
170 return syncer::ModelTypeToString(type());
173 DataTypeController::State NonUIDataTypeController::state() const {
177 void NonUIDataTypeController::OnSingleDatatypeUnrecoverableError(
178 const tracked_objects::Location& from_here, const std::string& message) {
179 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
180 RecordUnrecoverableError(from_here, message);
181 BrowserThread::PostTask(BrowserThread::UI, from_here,
182 base::Bind(&NonUIDataTypeController::DisableImpl,
188 NonUIDataTypeController::NonUIDataTypeController()
189 : profile_sync_factory_(NULL),
191 sync_service_(NULL) {}
193 NonUIDataTypeController::~NonUIDataTypeController() {}
195 void NonUIDataTypeController::StartDone(
196 DataTypeController::StartResult start_result,
197 const syncer::SyncMergeResult& local_merge_result,
198 const syncer::SyncMergeResult& syncer_merge_result) {
199 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
201 DataTypeController::State new_state;
202 if (IsSuccessfulResult(start_result)) {
205 new_state = (start_result == ASSOCIATION_FAILED ? DISABLED : NOT_RUNNING);
208 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
209 base::Bind(&NonUIDataTypeController::StartDoneImpl,
214 syncer_merge_result));
217 void NonUIDataTypeController::StartDoneImpl(
218 DataTypeController::StartResult start_result,
219 DataTypeController::State new_state,
220 const syncer::SyncMergeResult& local_merge_result,
221 const syncer::SyncMergeResult& syncer_merge_result) {
222 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
224 if (IsUnrecoverableResult(start_result))
225 RecordUnrecoverableError(FROM_HERE, "StartFailed");
227 // If we failed to start up, and we haven't been stopped yet, we need to
228 // ensure we clean up the local service and shared change processor properly.
229 if (new_state != RUNNING && state() != NOT_RUNNING && state() != STOPPING) {
230 ClearSharedChangeProcessor();
231 StopLocalServiceAsync();
234 // It's possible to have StartDoneImpl called first from the UI thread
235 // (due to Stop being called) and then posted from the non-UI thread. In
236 // this case, we drop the second call because we've already been stopped.
237 if (state_ == NOT_RUNNING) {
238 DCHECK(start_callback_.is_null());
243 if (state_ != RUNNING) {
246 RecordStartFailure(start_result);
249 // We have to release the callback before we call it, since it's possible
250 // invoking the callback will trigger a call to STOP(), which will get
251 // confused by the non-NULL start_callback_.
252 StartCallback callback = start_callback_;
253 start_callback_.Reset();
254 callback.Run(start_result, local_merge_result, syncer_merge_result);
257 void NonUIDataTypeController::RecordAssociationTime(base::TimeDelta time) {
258 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
259 #define PER_DATA_TYPE_MACRO(type_str) \
260 UMA_HISTOGRAM_TIMES("Sync." type_str "AssociationTime", time);
261 SYNC_DATA_TYPE_HISTOGRAM(type());
262 #undef PER_DATA_TYPE_MACRO
265 void NonUIDataTypeController::RecordStartFailure(StartResult result) {
266 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
267 UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeStartFailures",
268 ModelTypeToHistogramInt(type()),
269 syncer::MODEL_TYPE_COUNT);
270 #define PER_DATA_TYPE_MACRO(type_str) \
271 UMA_HISTOGRAM_ENUMERATION("Sync." type_str "StartFailure", result, \
273 SYNC_DATA_TYPE_HISTOGRAM(type());
274 #undef PER_DATA_TYPE_MACRO
277 void NonUIDataTypeController::AbortModelLoad() {
278 state_ = NOT_RUNNING;
280 ModelLoadCallback model_load_callback = model_load_callback_;
281 model_load_callback_.Reset();
282 model_load_callback.Run(type(),
283 syncer::SyncError(FROM_HERE,
284 syncer::SyncError::DATATYPE_ERROR,
289 void NonUIDataTypeController::DisableImpl(
290 const tracked_objects::Location& from_here,
291 const std::string& message) {
292 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
293 sync_service_->DisableBrokenDatatype(type(), from_here, message);
296 bool NonUIDataTypeController::StartAssociationAsync() {
297 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
298 DCHECK_EQ(state(), ASSOCIATING);
299 return PostTaskOnBackendThread(
302 &NonUIDataTypeController::StartAssociationWithSharedChangeProcessor,
304 shared_change_processor_));
307 // This method can execute after we've already stopped (and possibly even
308 // destroyed) both the Syncer and the SyncableService. As a result, all actions
309 // must either have no side effects outside of the DTC or must be protected
310 // by |shared_change_processor|, which is guaranteed to have been Disconnected
311 // if the syncer shut down.
312 void NonUIDataTypeController::
313 StartAssociationWithSharedChangeProcessor(
314 const scoped_refptr<SharedChangeProcessor>& shared_change_processor) {
315 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
316 DCHECK(shared_change_processor.get());
317 syncer::SyncMergeResult local_merge_result(type());
318 syncer::SyncMergeResult syncer_merge_result(type());
319 base::WeakPtrFactory<syncer::SyncMergeResult> weak_ptr_factory(
320 &syncer_merge_result);
322 // Connect |shared_change_processor| to the syncer and get the
323 // syncer::SyncableService associated with type().
324 // Note that it's possible the shared_change_processor has already been
325 // disconnected at this point, so all our accesses to the syncer from this
326 // point on are through it.
327 local_service_ = shared_change_processor->Connect(
328 profile_sync_factory_,
332 weak_ptr_factory.GetWeakPtr());
333 if (!local_service_.get()) {
334 syncer::SyncError error(FROM_HERE,
335 syncer::SyncError::DATATYPE_ERROR,
336 "Failed to connect to syncer.",
338 local_merge_result.set_error(error);
339 StartDone(ASSOCIATION_FAILED,
341 syncer_merge_result);
345 if (!shared_change_processor->CryptoReadyIfNecessary()) {
346 StartDone(NEEDS_CRYPTO,
348 syncer_merge_result);
352 bool sync_has_nodes = false;
353 if (!shared_change_processor->SyncModelHasUserCreatedNodes(&sync_has_nodes)) {
354 syncer::SyncError error(FROM_HERE,
355 syncer::SyncError::UNRECOVERABLE_ERROR,
356 "Failed to load sync nodes",
358 local_merge_result.set_error(error);
359 StartDone(UNRECOVERABLE_ERROR,
361 syncer_merge_result);
365 base::TimeTicks start_time = base::TimeTicks::Now();
366 syncer::SyncDataList initial_sync_data;
367 syncer::SyncError error =
368 shared_change_processor->GetAllSyncDataReturnError(
369 type(), &initial_sync_data);
371 local_merge_result.set_error(error);
372 StartDone(ASSOCIATION_FAILED,
374 syncer_merge_result);
378 syncer_merge_result.set_num_items_before_association(
379 initial_sync_data.size());
380 // Passes a reference to |shared_change_processor|.
382 local_service_->MergeDataAndStartSyncing(
385 scoped_ptr<syncer::SyncChangeProcessor>(
386 new SharedChangeProcessorRef(shared_change_processor)),
387 scoped_ptr<syncer::SyncErrorFactory>(
388 new SharedChangeProcessorRef(shared_change_processor)));
389 RecordAssociationTime(base::TimeTicks::Now() - start_time);
390 if (local_merge_result.error().IsSet()) {
391 StartDone(ASSOCIATION_FAILED,
393 syncer_merge_result);
397 syncer_merge_result.set_num_items_after_association(
398 shared_change_processor->GetSyncCount());
400 // If we've been disconnected, sync_service_ may return an invalid
401 // pointer, but |shared_change_processor| protects us from attempting to
403 // Note: This must be done on the datatype's thread to ensure local_service_
404 // doesn't start trying to push changes from its thread before we activate
406 shared_change_processor->ActivateDataType(model_safe_group());
407 StartDone(!sync_has_nodes ? OK_FIRST_RUN : OK,
409 syncer_merge_result);
412 void NonUIDataTypeController::ClearSharedChangeProcessor() {
413 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
414 // |shared_change_processor_| can already be NULL if Stop() is
415 // called after StartDoneImpl(_, DISABLED, _).
416 if (shared_change_processor_.get()) {
417 shared_change_processor_->Disconnect();
418 shared_change_processor_ = NULL;
422 void NonUIDataTypeController::StopLocalServiceAsync() {
423 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
424 PostTaskOnBackendThread(
426 base::Bind(&NonUIDataTypeController::StopLocalService, this));
429 void NonUIDataTypeController::StopLocalService() {
430 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
431 if (local_service_.get())
432 local_service_->StopSyncing(type());
433 local_service_.reset();
436 } // namespace browser_sync