Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / sync / glue / non_ui_data_type_controller.cc
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.
4
5 #include "chrome/browser/sync/glue/non_ui_data_type_controller.h"
6
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"
18
19 using content::BrowserThread;
20
21 namespace browser_sync {
22
23 NonUIDataTypeController::NonUIDataTypeController(
24     ProfileSyncComponentsFactory* profile_sync_factory,
25     Profile* profile,
26     ProfileSyncService* sync_service)
27     : profile_sync_factory_(profile_sync_factory),
28       profile_(profile),
29       sync_service_(sync_service),
30       state_(NOT_RUNNING) {
31 }
32
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",
42                                               type()));
43     return;
44   }
45
46   state_ = MODEL_STARTING;
47
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());
54
55   model_load_callback_ = model_load_callback;
56   if (!StartModels()) {
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);
60     return;
61   }
62
63   OnModelLoaded();
64 }
65
66 void NonUIDataTypeController::OnModelLoaded() {
67   DCHECK_EQ(state_, MODEL_STARTING);
68   DCHECK(!model_load_callback_.is_null());
69   state_ = MODEL_LOADED;
70
71   ModelLoadCallback model_load_callback = model_load_callback_;
72   model_load_callback_.Reset();
73   model_load_callback.Run(type(), syncer::SyncError());
74 }
75
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.
80   return true;
81 }
82
83 void NonUIDataTypeController::StopModels() {
84   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
85 }
86
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);
92   state_ = ASSOCIATING;
93
94   start_callback_ = start_callback;
95   if (!StartAssociationAsync()) {
96     syncer::SyncError error(
97         FROM_HERE,
98         syncer::SyncError::DATATYPE_ERROR,
99         "Failed to post StartAssociation",
100         type());
101     syncer::SyncMergeResult local_merge_result(type());
102     local_merge_result.set_error(error);
103     StartDoneImpl(ASSOCIATION_FAILED,
104                   NOT_RUNNING,
105                   local_merge_result,
106                   syncer::SyncMergeResult(type()));
107     // StartDoneImpl should have called ClearSharedChangeProcessor();
108     DCHECK(!shared_change_processor_.get());
109     return;
110   }
111 }
112
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.
117     NOTREACHED();
118     return;
119   }
120
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();
125
126   // If we haven't finished starting, we need to abort the start.
127   switch (state()) {
128     case MODEL_STARTING:
129       state_ = STOPPING;
130       AbortModelLoad();
131       return;  // The datatype was never activated, we're done.
132     case ASSOCIATING:
133       state_ = STOPPING;
134       StartDoneImpl(ABORTED,
135                     NOT_RUNNING,
136                     syncer::SyncMergeResult(type()),
137                     syncer::SyncMergeResult(type()));
138       // We continue on to deactivate the datatype and stop the local service.
139       break;
140     case MODEL_LOADED:
141     case DISABLED:
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;
146       StopModels();
147       return;
148     default:
149       // Datatype was fully started. Need to deactivate and stop the local
150       // service.
151       DCHECK_EQ(state(), RUNNING);
152       state_ = STOPPING;
153       StopModels();
154       break;
155   }
156
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());
160
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();
164
165   state_ = NOT_RUNNING;
166 }
167
168 std::string NonUIDataTypeController::name() const {
169   // For logging only.
170   return syncer::ModelTypeToString(type());
171 }
172
173 DataTypeController::State NonUIDataTypeController::state() const {
174   return state_;
175 }
176
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,
183                  this,
184                  from_here,
185                  message));
186 }
187
188 NonUIDataTypeController::NonUIDataTypeController()
189     : profile_sync_factory_(NULL),
190       profile_(NULL),
191       sync_service_(NULL) {}
192
193 NonUIDataTypeController::~NonUIDataTypeController() {}
194
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));
200
201   DataTypeController::State new_state;
202   if (IsSuccessfulResult(start_result)) {
203     new_state = RUNNING;
204   } else {
205     new_state = (start_result == ASSOCIATION_FAILED ? DISABLED : NOT_RUNNING);
206   }
207
208   BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
209       base::Bind(&NonUIDataTypeController::StartDoneImpl,
210                  this,
211                  start_result,
212                  new_state,
213                  local_merge_result,
214                  syncer_merge_result));
215 }
216
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));
223
224   if (IsUnrecoverableResult(start_result))
225     RecordUnrecoverableError(FROM_HERE, "StartFailed");
226
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();
232   }
233
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());
239     return;
240   }
241
242   state_ = new_state;
243   if (state_ != RUNNING) {
244     // Start failed.
245     StopModels();
246     RecordStartFailure(start_result);
247   }
248
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);
255 }
256
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
263 }
264
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, \
272                               MAX_START_RESULT);
273   SYNC_DATA_TYPE_HISTOGRAM(type());
274 #undef PER_DATA_TYPE_MACRO
275 }
276
277 void NonUIDataTypeController::AbortModelLoad() {
278   state_ = NOT_RUNNING;
279   StopModels();
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,
285                                             "ABORTED",
286                                             type()));
287 }
288
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);
294 }
295
296 bool NonUIDataTypeController::StartAssociationAsync() {
297   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
298   DCHECK_EQ(state(), ASSOCIATING);
299   return PostTaskOnBackendThread(
300       FROM_HERE,
301       base::Bind(
302           &NonUIDataTypeController::StartAssociationWithSharedChangeProcessor,
303           this,
304           shared_change_processor_));
305 }
306
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);
321
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_,
329       sync_service_,
330       this,
331       type(),
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.",
337                             type());
338     local_merge_result.set_error(error);
339     StartDone(ASSOCIATION_FAILED,
340               local_merge_result,
341               syncer_merge_result);
342     return;
343   }
344
345   if (!shared_change_processor->CryptoReadyIfNecessary()) {
346     StartDone(NEEDS_CRYPTO,
347               local_merge_result,
348               syncer_merge_result);
349     return;
350   }
351
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",
357                             type());
358     local_merge_result.set_error(error);
359     StartDone(UNRECOVERABLE_ERROR,
360               local_merge_result,
361               syncer_merge_result);
362     return;
363   }
364
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);
370   if (error.IsSet()) {
371     local_merge_result.set_error(error);
372     StartDone(ASSOCIATION_FAILED,
373               local_merge_result,
374               syncer_merge_result);
375     return;
376   }
377
378   syncer_merge_result.set_num_items_before_association(
379       initial_sync_data.size());
380   // Passes a reference to |shared_change_processor|.
381   local_merge_result =
382       local_service_->MergeDataAndStartSyncing(
383           type(),
384           initial_sync_data,
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,
392               local_merge_result,
393               syncer_merge_result);
394     return;
395   }
396
397   syncer_merge_result.set_num_items_after_association(
398       shared_change_processor->GetSyncCount());
399
400   // If we've been disconnected, sync_service_ may return an invalid
401   // pointer, but |shared_change_processor| protects us from attempting to
402   // access it.
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
405   // the datatype.
406   shared_change_processor->ActivateDataType(model_safe_group());
407   StartDone(!sync_has_nodes ? OK_FIRST_RUN : OK,
408             local_merge_result,
409             syncer_merge_result);
410 }
411
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;
419   }
420 }
421
422 void NonUIDataTypeController::StopLocalServiceAsync() {
423   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
424   PostTaskOnBackendThread(
425       FROM_HERE,
426       base::Bind(&NonUIDataTypeController::StopLocalService, this));
427 }
428
429 void NonUIDataTypeController::StopLocalService() {
430   DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
431   if (local_service_.get())
432     local_service_->StopSyncing(type());
433   local_service_.reset();
434 }
435
436 }  // namespace browser_sync