1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "base/file_util.h"
#include "base/file_version_info.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/glue/change_processor.h"
#include "chrome/browser/sync/glue/database_model_worker.h"
#include "chrome/browser/sync/glue/history_model_worker.h"
#include "chrome/browser/sync/glue/sync_backend_host.h"
#include "chrome/browser/sync/glue/http_bridge.h"
#include "chrome/browser/sync/sessions/session_state.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "webkit/glue/webkit_glue.h"
static const int kSaveChangesIntervalSeconds = 10;
static const char kGaiaServiceId[] = "chromiumsync";
static const char kGaiaSourceForChrome[] = "ChromiumBrowser";
static const FilePath::CharType kSyncDataFolderName[] =
FILE_PATH_LITERAL("Sync Data");
using browser_sync::DataTypeController;
typedef GoogleServiceAuthError AuthError;
namespace browser_sync {
using sessions::SyncSessionSnapshot;
SyncBackendHost::SyncBackendHost(
SyncFrontend* frontend,
Profile* profile,
const FilePath& profile_path,
const DataTypeController::TypeMap& data_type_controllers)
: core_thread_("Chrome_SyncCoreThread"),
frontend_loop_(MessageLoop::current()),
profile_(profile),
frontend_(frontend),
sync_data_folder_path_(profile_path.Append(kSyncDataFolderName)),
data_type_controllers_(data_type_controllers),
last_auth_error_(AuthError::None()) {
core_ = new Core(this);
}
SyncBackendHost::SyncBackendHost()
: core_thread_("Chrome_SyncCoreThread"),
frontend_loop_(MessageLoop::current()),
frontend_(NULL),
last_auth_error_(AuthError::None()) {
}
SyncBackendHost::~SyncBackendHost() {
DCHECK(!core_ && !frontend_) << "Must call Shutdown before destructor.";
DCHECK(registrar_.workers.empty());
}
void SyncBackendHost::Initialize(
const GURL& sync_service_url,
URLRequestContextGetter* baseline_context_getter,
const std::string& lsid,
bool delete_sync_data_folder,
bool invalidate_sync_login,
bool invalidate_sync_xmpp_login,
NotificationMethod notification_method) {
if (!core_thread_.Start())
return;
// Create a worker for the UI thread and route bookmark changes to it.
// TODO(tim): Pull this into a method to reuse. For now we don't even
// need to lock because we init before the syncapi exists and we tear down
// after the syncapi is destroyed. Make sure to NULL-check workers_ indices
// when a new type is synced as the worker may already exist and you just
// need to update routing_info_.
registrar_.workers[GROUP_DB] = new DatabaseModelWorker();
registrar_.workers[GROUP_HISTORY] =
new HistoryModelWorker(
profile_->GetHistoryService(Profile::IMPLICIT_ACCESS));
registrar_.workers[GROUP_UI] = new UIModelWorker(frontend_loop_);
registrar_.workers[GROUP_PASSIVE] = new ModelSafeWorker();
// Any datatypes that we want the syncer to pull down must
// be in the routing_info map. We set them to group passive, meaning that
// updates will be applied, but not dispatched to the UI thread yet.
for (DataTypeController::TypeMap::const_iterator it =
data_type_controllers_.begin();
it != data_type_controllers_.end(); ++it) {
registrar_.routing_info[(*it).first] = GROUP_PASSIVE;
}
core_thread_.message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(core_.get(), &SyncBackendHost::Core::DoInitialize,
Core::DoInitializeOptions(
sync_service_url, true,
new HttpBridgeFactory(baseline_context_getter),
new HttpBridgeFactory(baseline_context_getter),
lsid,
delete_sync_data_folder,
invalidate_sync_login,
invalidate_sync_xmpp_login,
notification_method)));
}
void SyncBackendHost::Authenticate(const std::string& username,
const std::string& password,
const std::string& captcha) {
core_thread_.message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(core_.get(), &SyncBackendHost::Core::DoAuthenticate,
username, password, captcha));
}
void SyncBackendHost::Shutdown(bool sync_disabled) {
// Thread shutdown should occur in the following order:
// - SyncerThread
// - CoreThread
// - UI Thread (stops some time after we return from this call).
core_thread_.message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(core_.get(),
&SyncBackendHost::Core::DoShutdown,
sync_disabled));
// Before joining the core_thread_, we wait for the UIModelWorker to
// give us the green light that it is not depending on the frontend_loop_ to
// process any more tasks. Stop() blocks until this termination condition
// is true.
if (ui_worker())
ui_worker()->Stop();
// Stop will return once the thread exits, which will be after DoShutdown
// runs. DoShutdown needs to run from core_thread_ because the sync backend
// requires any thread that opened sqlite handles to relinquish them
// personally. We need to join threads, because otherwise the main Chrome
// thread (ui loop) can exit before DoShutdown finishes, at which point
// virtually anything the sync backend does (or the post-back to
// frontend_loop_ by our Core) will epically fail because the CRT won't be
// initialized. For now this only ever happens at sync-enabled-Chrome exit,
// meaning bug 1482548 applies to prolonged "waiting" that may occur in
// DoShutdown.
core_thread_.Stop();
registrar_.routing_info.clear();
registrar_.workers[GROUP_DB] = NULL;
registrar_.workers[GROUP_HISTORY] = NULL;
registrar_.workers[GROUP_UI] = NULL;
registrar_.workers[GROUP_PASSIVE] = NULL;
registrar_.workers.erase(GROUP_DB);
registrar_.workers.erase(GROUP_HISTORY);
registrar_.workers.erase(GROUP_UI);
registrar_.workers.erase(GROUP_PASSIVE);
frontend_ = NULL;
core_ = NULL; // Releases reference to core_.
}
void SyncBackendHost::ActivateDataType(
DataTypeController* data_type_controller,
ChangeProcessor* change_processor) {
// TODO(skrul): Add some kind of lock here that prevents concurrent
// calls.
// Ensure that the given data type is in the PASSIVE group.
browser_sync::ModelSafeRoutingInfo::iterator i =
registrar_.routing_info.find(data_type_controller->type());
DCHECK(i != registrar_.routing_info.end());
DCHECK((*i).second == GROUP_PASSIVE);
syncable::ModelType type = data_type_controller->type();
// Change the data type's routing info to its group.
registrar_.routing_info[type] = data_type_controller->model_safe_group();
// Add the data type's change processor to the list of change
// processors so it can receive updates.
DCHECK(processors_.count(type) == 0);
processors_[type] = change_processor;
}
void SyncBackendHost::DeactivateDataType(
DataTypeController* data_type_controller,
ChangeProcessor* change_processor) {
registrar_.routing_info.erase(data_type_controller->type());
std::map<syncable::ModelType, ChangeProcessor*>::size_type erased =
processors_.erase(data_type_controller->type());
DCHECK(erased == 1);
// TODO(sync): At this point we need to purge the data associated
// with this data type from the sync db.
}
bool SyncBackendHost::RequestPause() {
return core_->syncapi()->RequestPause();
}
bool SyncBackendHost::RequestResume() {
return core_->syncapi()->RequestResume();
}
void SyncBackendHost::Core::NotifyFrontend(FrontendNotification notification) {
if (!host_ || !host_->frontend_) {
return; // This can happen in testing because the UI loop processes tasks
// after an instance of SyncBackendHost was destroyed. In real
// life this doesn't happen.
}
switch (notification) {
case INITIALIZED:
host_->frontend_->OnBackendInitialized();
return;
case SYNC_CYCLE_COMPLETED:
host_->frontend_->OnSyncCycleCompleted();
return;
}
}
void SyncBackendHost::Core::NotifyPaused() {
NotificationService::current()->Notify(NotificationType::SYNC_PAUSED,
NotificationService::AllSources(),
NotificationService::NoDetails());
}
void SyncBackendHost::Core::NotifyResumed() {
NotificationService::current()->Notify(NotificationType::SYNC_RESUMED,
NotificationService::AllSources(),
NotificationService::NoDetails());
}
SyncBackendHost::UserShareHandle SyncBackendHost::GetUserShareHandle() const {
return core_->syncapi()->GetUserShare();
}
SyncBackendHost::Status SyncBackendHost::GetDetailedStatus() {
return core_->syncapi()->GetDetailedStatus();
}
SyncBackendHost::StatusSummary SyncBackendHost::GetStatusSummary() {
return core_->syncapi()->GetStatusSummary();
}
string16 SyncBackendHost::GetAuthenticatedUsername() const {
return UTF8ToUTF16(core_->syncapi()->GetAuthenticatedUsername());
}
const GoogleServiceAuthError& SyncBackendHost::GetAuthError() const {
return last_auth_error_;
}
const SyncSessionSnapshot* SyncBackendHost::GetLastSessionSnapshot() const {
return last_snapshot_.get();
}
void SyncBackendHost::GetWorkers(std::vector<ModelSafeWorker*>* out) {
AutoLock lock(registrar_lock_);
out->clear();
for (WorkerMap::const_iterator it = registrar_.workers.begin();
it != registrar_.workers.end(); ++it) {
out->push_back((*it).second);
}
}
void SyncBackendHost::GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) {
AutoLock lock(registrar_lock_);
ModelSafeRoutingInfo copy(registrar_.routing_info);
out->swap(copy);
}
SyncBackendHost::Core::Core(SyncBackendHost* backend)
: host_(backend),
syncapi_(new sync_api::SyncManager()) {
}
// Helper to construct a user agent string (ASCII) suitable for use by
// the syncapi for any HTTP communication. This string is used by the sync
// backend for classifying client types when calculating statistics.
std::string MakeUserAgentForSyncapi() {
std::string user_agent;
user_agent = "Chrome ";
#if defined(OS_WIN)
user_agent += "WIN ";
#elif defined(OS_LINUX)
user_agent += "LINUX ";
#elif defined(OS_FREEBSD)
user_agent += "FREEBSD ";
#elif defined(OS_OPENBSD)
user_agent += "OPENBSD ";
#elif defined(OS_MACOSX)
user_agent += "MAC ";
#endif
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
if (version_info == NULL) {
DLOG(ERROR) << "Unable to create FileVersionInfo object";
return user_agent;
}
user_agent += WideToASCII(version_info->product_version());
user_agent += " (" + WideToASCII(version_info->last_change()) + ")";
if (!version_info->is_official_build())
user_agent += "-devel";
return user_agent;
}
void SyncBackendHost::Core::DoInitialize(const DoInitializeOptions& options) {
DCHECK(MessageLoop::current() == host_->core_thread_.message_loop());
// Blow away the partial or corrupt sync data folder before doing any more
// initialization, if necessary.
if (options.delete_sync_data_folder)
DeleteSyncDataFolder();
// Make sure that the directory exists before initializing the backend.
// If it already exists, this will do no harm.
bool success = file_util::CreateDirectory(host_->sync_data_folder_path());
DCHECK(success);
syncapi_->SetObserver(this);
const FilePath& path_str = host_->sync_data_folder_path();
success = syncapi_->Init(path_str,
(options.service_url.host() + options.service_url.path()).c_str(),
options.service_url.EffectiveIntPort(),
kGaiaServiceId,
kGaiaSourceForChrome,
options.service_url.SchemeIsSecure(),
options.http_bridge_factory,
options.auth_http_bridge_factory,
host_, // ModelSafeWorkerRegistrar.
options.attempt_last_user_authentication,
options.invalidate_sync_login,
options.invalidate_sync_xmpp_login,
MakeUserAgentForSyncapi().c_str(),
options.lsid.c_str(),
options.notification_method);
DCHECK(success) << "Syncapi initialization failed!";
}
void SyncBackendHost::Core::DoAuthenticate(const std::string& username,
const std::string& password,
const std::string& captcha) {
DCHECK(MessageLoop::current() == host_->core_thread_.message_loop());
syncapi_->Authenticate(username.c_str(), password.c_str(), captcha.c_str());
}
UIModelWorker* SyncBackendHost::ui_worker() {
ModelSafeWorker* w = registrar_.workers[GROUP_UI];
if (w == NULL)
return NULL;
if (w->GetModelSafeGroup() != GROUP_UI)
NOTREACHED();
return static_cast<UIModelWorker*>(w);
}
void SyncBackendHost::Core::DoShutdown(bool sync_disabled) {
DCHECK(MessageLoop::current() == host_->core_thread_.message_loop());
save_changes_timer_.Stop();
syncapi_->Shutdown(); // Stops the SyncerThread.
syncapi_->RemoveObserver();
host_->ui_worker()->OnSyncerShutdownComplete();
if (sync_disabled)
DeleteSyncDataFolder();
host_ = NULL;
}
void SyncBackendHost::Core::OnChangesApplied(
syncable::ModelType model_type,
const sync_api::BaseTransaction* trans,
const sync_api::SyncManager::ChangeRecord* changes,
int change_count) {
if (!host_ || !host_->frontend_) {
DCHECK(false) << "OnChangesApplied called after Shutdown?";
return;
}
std::map<syncable::ModelType, ChangeProcessor*>::const_iterator it =
host_->processors_.find(model_type);
// Until model association happens for a datatype, it will not appear in
// the processors list. During this time, it is OK to drop changes on
// the floor (since model association has not happened yet). When the
// data type is activated, model association takes place then the change
// processor is added to the processors_ list. This all happens on
// the UI thread so we will never drop any changes after model
// association.
if (it == host_->processors_.end())
return;
ChangeProcessor* processor = it->second;
// Ensure the change processor is willing to accept changes.
if (!processor->IsRunning())
return;
processor->ApplyChangesFromSyncModel(trans, changes, change_count);
}
void SyncBackendHost::Core::OnSyncCycleCompleted(
const SyncSessionSnapshot* snapshot) {
host_->frontend_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&Core::HandleSyncCycleCompletedOnFrontendLoop,
new SyncSessionSnapshot(*snapshot)));
}
void SyncBackendHost::Core::HandleSyncCycleCompletedOnFrontendLoop(
SyncSessionSnapshot* snapshot) {
if (!host_ || !host_->frontend_)
return;
DCHECK_EQ(MessageLoop::current(), host_->frontend_loop_);
host_->last_snapshot_.reset(snapshot);
host_->frontend_->OnSyncCycleCompleted();
}
void SyncBackendHost::Core::OnInitializationComplete() {
if (!host_ || !host_->frontend_)
return; // We may have been told to Shutdown before initialization
// completed.
// We could be on some random sync backend thread, so MessageLoop::current()
// can definitely be null in here.
host_->frontend_loop_->PostTask(FROM_HERE,
NewRunnableMethod(this, &Core::NotifyFrontend, INITIALIZED));
// Initialization is complete, so we can schedule recurring SaveChanges.
host_->core_thread_.message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(this, &Core::StartSavingChanges));
}
void SyncBackendHost::Core::OnAuthError(const AuthError& auth_error) {
// We could be on SyncEngine_AuthWatcherThread. Post to our core loop so
// we can modify state.
host_->frontend_loop_->PostTask(FROM_HERE,
NewRunnableMethod(this, &Core::HandleAuthErrorEventOnFrontendLoop,
auth_error));
}
void SyncBackendHost::Core::OnPaused() {
host_->frontend_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &Core::NotifyPaused));
}
void SyncBackendHost::Core::OnResumed() {
host_->frontend_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &Core::NotifyResumed));
}
void SyncBackendHost::Core::HandleAuthErrorEventOnFrontendLoop(
const GoogleServiceAuthError& new_auth_error) {
if (!host_ || !host_->frontend_)
return;
DCHECK_EQ(MessageLoop::current(), host_->frontend_loop_);
host_->last_auth_error_ = new_auth_error;
host_->frontend_->OnAuthError();
}
void SyncBackendHost::Core::StartSavingChanges() {
save_changes_timer_.Start(
base::TimeDelta::FromSeconds(kSaveChangesIntervalSeconds),
this, &Core::SaveChanges);
}
void SyncBackendHost::Core::SaveChanges() {
syncapi_->SaveChanges();
}
void SyncBackendHost::Core::DeleteSyncDataFolder() {
if (file_util::DirectoryExists(host_->sync_data_folder_path())) {
if (!file_util::Delete(host_->sync_data_folder_path(), true))
LOG(DFATAL) << "Could not delete the Sync Data folder.";
}
}
} // namespace browser_sync
|