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

Side by Side Diff: chrome/browser/sync/engine/syncer_thread2.cc

Issue 5939006: sync: beginnings of MessageLoop based SyncerThread (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: review+tests Created 9 years, 11 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 | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2011 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/engine/syncer_thread2.h"
6
7 #include "base/rand_util.h"
8 #include "chrome/browser/sync/engine/syncer.h"
9
10 using base::TimeDelta;
11 using base::TimeTicks;
12
13 namespace browser_sync {
14
15 using sessions::SyncSession;
16 using sessions::SyncSessionSnapshot;
17 using sessions::SyncSourceInfo;
18 using syncable::ModelTypeBitSet;
19 using sync_pb::GetUpdatesCallerInfo;
20
21 namespace s3 {
22
23 SyncerThread::DelayProvider::DelayProvider() {}
24 SyncerThread::DelayProvider::~DelayProvider() {}
25
26 TimeDelta SyncerThread::DelayProvider::GetDelay(
27 const base::TimeDelta& last_delay) {
28 return SyncerThread::GetRecommendedDelay(last_delay);
29 }
30
31 SyncerThread::WaitInterval::WaitInterval(Mode mode, TimeDelta length)
32 : mode(mode), length(length), had_nudge(false) { }
33
34 SyncerThread::SyncerThread(sessions::SyncSessionContext* context,
35 Syncer* syncer)
36 : thread_("SyncEngine_SyncerThread"),
37 syncer_short_poll_interval_seconds_(
38 TimeDelta::FromSeconds(kDefaultShortPollIntervalSeconds)),
39 syncer_long_poll_interval_seconds_(
40 TimeDelta::FromSeconds(kDefaultLongPollIntervalSeconds)),
41 server_connection_ok_(false),
42 delay_provider_(new DelayProvider()),
43 syncer_(syncer),
44 session_context_(context) {
45 }
46
47 SyncerThread::~SyncerThread() {
48 DCHECK(!thread_.IsRunning());
49 }
50
51 void SyncerThread::Start(Mode mode) {
52 if (!thread_.IsRunning() && !thread_.Start()) {
53 NOTREACHED() << "Unable to start SyncerThread.";
54 return;
55 }
56
57 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
58 this, &SyncerThread::StartImpl, mode));
59 }
60
61 void SyncerThread::StartImpl(Mode mode) {
62 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
63 DCHECK(!session_context_->account_name().empty());
64 DCHECK(syncer_.get());
65 mode_ = mode;
66 AdjustPolling(NULL); // Will kick start poll timer if needed.
67 }
68
69 bool SyncerThread::ShouldRunJob(SyncSessionJob::Purpose purpose,
70 const TimeTicks& scheduled_start) {
71 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
72
73 // Check wait interval.
74 if (wait_interval_.get()) {
75 if (wait_interval_->mode == WaitInterval::THROTTLED)
76 return false;
77
78 DCHECK_EQ(wait_interval_->mode, WaitInterval::EXPONENTIAL_BACKOFF);
79 DCHECK(purpose == SyncSessionJob::POLL ||
80 purpose == SyncSessionJob::NUDGE);
81 if ((purpose != SyncSessionJob::NUDGE) || wait_interval_->had_nudge)
82 return false;
83 }
84
85 // Mode / purpose contract (See 'Mode' enum in header). Don't run jobs that
86 // were intended for a normal sync if we are in configuration mode, and vice
87 // versa.
88 switch (mode_) {
89 case CONFIGURATION_MODE:
90 if (purpose != SyncSessionJob::CONFIGURATION)
91 return false;
92 break;
93 case NORMAL_MODE:
94 if (purpose != SyncSessionJob::POLL && purpose != SyncSessionJob::NUDGE)
95 return false;
96 break;
97 default:
98 NOTREACHED() << "Unknown SyncerThread Mode: " << mode_;
99 return false;
100 }
101
102 // Continuation NUDGE tasks have priority over POLLs because they are the
103 // only tasks that trigger exponential backoff, so this prevents them from
104 // being starved from running (e.g. due to a very, very low poll interval,
105 // such as 0ms). It's rare that this would ever matter in practice.
106 if (purpose == SyncSessionJob::POLL && (pending_nudge_.get() &&
107 pending_nudge_->session->source().first ==
108 GetUpdatesCallerInfo::SYNC_CYCLE_CONTINUATION)) {
109 return false;
110 }
111
112 // Freshness condition.
113 if (purpose == SyncSessionJob::NUDGE &&
114 (scheduled_start < last_sync_session_end_time_)) {
115 return false;
116 }
117
118 return server_connection_ok_;
119 }
120
121 namespace {
122 GetUpdatesCallerInfo::GetUpdatesSource GetUpdatesFromNudgeSource(
123 NudgeSource source) {
124 switch (source) {
125 case NUDGE_SOURCE_NOTIFICATION:
126 return GetUpdatesCallerInfo::NOTIFICATION;
127 case NUDGE_SOURCE_LOCAL:
128 return GetUpdatesCallerInfo::LOCAL;
129 case NUDGE_SOURCE_CONTINUATION:
130 return GetUpdatesCallerInfo::SYNC_CYCLE_CONTINUATION;
131 case NUDGE_SOURCE_CLEAR_PRIVATE_DATA:
132 return GetUpdatesCallerInfo::CLEAR_PRIVATE_DATA;
133 case NUDGE_SOURCE_UNKNOWN:
134 default:
135 return GetUpdatesCallerInfo::UNKNOWN;
136 }
137 }
138
139 // Functor for std::find_if to search by ModelSafeGroup.
140 struct WorkerGroupIs {
141 explicit WorkerGroupIs(ModelSafeGroup group) : group(group) {}
142 bool operator()(ModelSafeWorker* w) {
143 return group == w->GetModelSafeGroup();
144 }
145 ModelSafeGroup group;
146 };
147 } // namespace
148
149 void SyncerThread::ScheduleNudge(const TimeDelta& delay,
150 NudgeSource source, const ModelTypeBitSet& types) {
151 if (!thread_.IsRunning()) {
152 NOTREACHED();
153 return;
154 }
155
156 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
157 this, &SyncerThread::ScheduleNudgeImpl, delay, source, types));
158 }
159
160 void SyncerThread::ScheduleNudgeImpl(const TimeDelta& delay,
161 NudgeSource source, const ModelTypeBitSet& model_types) {
162 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
163 TimeTicks rough_start = TimeTicks::Now() + delay;
164 if (!ShouldRunJob(SyncSessionJob::NUDGE, rough_start))
165 return;
166
167 // Note we currently nudge for all types regardless of the ones incurring
168 // the nudge. Doing different would throw off some syncer commands like
169 // CleanupDisabledTypes. We may want to change this in the future.
170 ModelSafeRoutingInfo routes;
171 std::vector<ModelSafeWorker*> workers;
172 session_context_->registrar()->GetModelSafeRoutingInfo(&routes);
173 session_context_->registrar()->GetWorkers(&workers);
174 SyncSourceInfo info(GetUpdatesFromNudgeSource(source), model_types);
175
176 scoped_ptr<SyncSession> session(new SyncSession(
177 session_context_.get(), this, info, routes, workers));
178
179 if (pending_nudge_.get()) {
180 if (IsBackingOff() && delay > TimeDelta::FromSeconds(1))
181 return;
182
183 pending_nudge_->session->Coalesce(session.get());
184 if (!IsBackingOff()) {
185 return;
186 } else {
187 // Re-schedule the current pending nudge.
188 SyncSession* s = pending_nudge_->session.get();
189 session.reset(new SyncSession(s->context(), s->delegate(), s->source(),
190 s->routing_info(), s->workers()));
191 pending_nudge_.reset();
192 }
193 }
194 ScheduleSyncSessionJob(delay, SyncSessionJob::NUDGE, session.release());
195 }
196
197 // Helper to extract the routing info and workers corresponding to types in
198 // |types| from |registrar|.
199 void GetModelSafeParamsForTypes(const ModelTypeBitSet& types,
200 ModelSafeWorkerRegistrar* registrar, ModelSafeRoutingInfo* routes,
201 std::vector<ModelSafeWorker*>* workers) {
202 ModelSafeRoutingInfo r_tmp;
203 std::vector<ModelSafeWorker*> w_tmp;
204 registrar->GetModelSafeRoutingInfo(&r_tmp);
205 registrar->GetWorkers(&w_tmp);
206
207 typedef std::vector<ModelSafeWorker*>::const_iterator iter;
208 for (size_t i = syncable::FIRST_REAL_MODEL_TYPE; i < types.size(); ++i) {
209 if (!types.test(i))
210 continue;
211 syncable::ModelType t = syncable::ModelTypeFromInt(i);
212 DCHECK_EQ(1U, r_tmp.count(t));
213 (*routes)[t] = r_tmp[t];
214 iter it = std::find_if(w_tmp.begin(), w_tmp.end(), WorkerGroupIs(r_tmp[t]));
215 if (it != w_tmp.end())
216 workers->push_back(*it);
217 else
218 NOTREACHED();
219 }
220
221 iter it = std::find_if(w_tmp.begin(), w_tmp.end(),
222 WorkerGroupIs(GROUP_PASSIVE));
223 if (it != w_tmp.end())
224 workers->push_back(*it);
225 else
226 NOTREACHED();
227 }
228
229 void SyncerThread::ScheduleConfig(const TimeDelta& delay,
230 const ModelTypeBitSet& types) {
231 if (!thread_.IsRunning()) {
232 NOTREACHED();
233 return;
234 }
235
236 ModelSafeRoutingInfo routes;
237 std::vector<ModelSafeWorker*> workers;
238 GetModelSafeParamsForTypes(types, session_context_->registrar(),
239 &routes, &workers);
240
241 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
242 this, &SyncerThread::ScheduleConfigImpl, delay, routes, workers));
243 }
244
245 void SyncerThread::ScheduleConfigImpl(const TimeDelta& delay,
246 const ModelSafeRoutingInfo& routing_info,
247 const std::vector<ModelSafeWorker*>& workers) {
248 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
249 NOTIMPLEMENTED() << "TODO(tim)";
250 }
251
252 void SyncerThread::ScheduleSyncSessionJob(const base::TimeDelta& delay,
253 SyncSessionJob::Purpose purpose, sessions::SyncSession* session) {
254 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
255 SyncSessionJob job = {purpose, TimeTicks::Now() + delay,
256 make_linked_ptr(session)};
257 if (purpose == SyncSessionJob::NUDGE) {
258 DCHECK(!pending_nudge_.get() || pending_nudge_->session.get() == session);
259 pending_nudge_.reset(new SyncSessionJob(job));
260 }
261 MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(this,
262 &SyncerThread::DoSyncSessionJob, job), delay.InMilliseconds());
263 }
264
265 void SyncerThread::DoSyncSessionJob(const SyncSessionJob& job) {
266 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
267
268 if (job.purpose == SyncSessionJob::NUDGE) {
269 DCHECK(pending_nudge_.get());
270 if (pending_nudge_->session != job.session)
271 return; // Another nudge must have been scheduled in in the meantime.
272 pending_nudge_.reset();
273 } else if (job.purpose == SyncSessionJob::CONFIGURATION) {
274 NOTIMPLEMENTED() << "TODO(tim): SyncShare [DOWNLOAD_UPDATES,APPLY_UPDATES]";
275 }
276
277 bool has_more_to_sync = true;
278 bool did_job = false;
279 while (ShouldRunJob(job.purpose, job.scheduled_start) && has_more_to_sync) {
280 VLOG(1) << "SyncerThread: Calling SyncShare.";
281 did_job = true;
282 // Synchronously perform the sync session from this thread.
283 syncer_->SyncShare(job.session.get());
284 has_more_to_sync = job.session->HasMoreToSync();
285 if (has_more_to_sync)
286 job.session->ResetTransientState();
287 }
288 VLOG(1) << "SyncerThread: Done SyncShare looping.";
289 if (did_job)
290 FinishSyncSessionJob(job);
291 }
292
293 void SyncerThread::FinishSyncSessionJob(const SyncSessionJob& job) {
294 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
295 // Update timing information for how often datatypes are triggering nudges.
296 base::TimeTicks now = TimeTicks::Now();
297 for (size_t i = syncable::FIRST_REAL_MODEL_TYPE;
298 i < job.session->source().second.size() &&
299 !last_sync_session_end_time_.is_null();
300 ++i) {
301 if (job.session->source().second[i]) {
302 syncable::PostTimeToTypeHistogram(syncable::ModelTypeFromInt(i),
303 now - last_sync_session_end_time_);
304 }
305 }
306 last_sync_session_end_time_ = now;
307 if (IsSyncingCurrentlySilenced())
308 return; // Nothing to do.
309
310 VLOG(1) << "Updating the next polling time after SyncMain";
311 ScheduleNextSync(job);
312 }
313
314 void SyncerThread::ScheduleNextSync(const SyncSessionJob& old_job) {
315 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
316 DCHECK(!old_job.session->HasMoreToSync());
317 // Note: |num_server_changes_remaining| > 0 here implies that we received a
318 // broken response while trying to download all updates, because the Syncer
319 // will loop until this value is exhausted. Also, if unsynced_handles exist
320 // but HasMoreToSync is false, this implies that the Syncer determined no
321 // forward progress was possible at this time (an error, such as an HTTP
322 // 500, is likely to have occurred during commit).
323 const bool work_to_do =
324 old_job.session->status_controller()->num_server_changes_remaining() > 0
325 || old_job.session->status_controller()->unsynced_handles().size() > 0;
326 VLOG(1) << "syncer has work to do: " << work_to_do;
327
328 AdjustPolling(&old_job);
329
330 // TODO(tim): Old impl had special code if notifications disabled. Needed?
331 if (!work_to_do) {
332 wait_interval_.reset(); // Success implies backoff relief.
333 return;
334 }
335
336 if (old_job.session->source().first ==
337 GetUpdatesCallerInfo::SYNC_CYCLE_CONTINUATION) {
338 // We don't seem to have made forward progress. Start or extend backoff.
339 HandleConsecutiveContinuationError(old_job);
340 } else if (IsBackingOff()) {
341 // We weren't continuing but we're in backoff; must have been a nudge.
342 DCHECK_EQ(SyncSessionJob::NUDGE, old_job.purpose);
343 DCHECK(!wait_interval_->had_nudge);
344 wait_interval_->had_nudge = true;
345 wait_interval_->timer.Reset();
346 } else {
347 // We weren't continuing and we aren't in backoff. Schedule a normal
348 // continuation.
349 ScheduleNudgeImpl(TimeDelta::FromSeconds(0), NUDGE_SOURCE_CONTINUATION,
350 old_job.session->source().second);
351 }
352 }
353
354 void SyncerThread::AdjustPolling(const SyncSessionJob* old_job) {
355 DCHECK(thread_.IsRunning());
356 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
357
358 TimeDelta poll = (!session_context_->notifications_enabled()) ?
359 syncer_short_poll_interval_seconds_ :
360 syncer_long_poll_interval_seconds_;
361 bool rate_changed = !poll_timer_.IsRunning() ||
362 poll != poll_timer_.GetCurrentDelay();
363
364 if (old_job && old_job->purpose != SyncSessionJob::POLL && !rate_changed)
365 poll_timer_.Reset();
366
367 if (!rate_changed)
368 return;
369
370 // Adjust poll rate.
371 poll_timer_.Stop();
372 poll_timer_.Start(poll, this, &SyncerThread::PollTimerCallback);
373 }
374
375 void SyncerThread::HandleConsecutiveContinuationError(
376 const SyncSessionJob& old_job) {
377 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
378 DCHECK(!IsBackingOff() || !wait_interval_->timer.IsRunning());
379 SyncSession* old = old_job.session.get();
380 SyncSession* s(new SyncSession(session_context_.get(), this,
381 old->source(), old->routing_info(), old->workers()));
382 TimeDelta length = delay_provider_->GetDelay(
383 IsBackingOff() ? wait_interval_->length : TimeDelta::FromSeconds(1));
384 wait_interval_.reset(new WaitInterval(WaitInterval::EXPONENTIAL_BACKOFF,
385 length));
386 SyncSessionJob job = {SyncSessionJob::NUDGE, TimeTicks::Now() + length,
387 make_linked_ptr(s)};
388 pending_nudge_.reset(new SyncSessionJob(job));
389 wait_interval_->timer.Start(length, this, &SyncerThread::DoCanaryJob);
390 }
391
392 // static
393 TimeDelta SyncerThread::GetRecommendedDelay(const TimeDelta& last_delay) {
394 if (last_delay.InSeconds() >= kMaxBackoffSeconds)
395 return TimeDelta::FromSeconds(kMaxBackoffSeconds);
396
397 // This calculates approx. base_delay_seconds * 2 +/- base_delay_seconds / 2
398 int64 backoff_s =
399 std::max(1LL, last_delay.InSeconds() * kBackoffRandomizationFactor);
400
401 // Flip a coin to randomize backoff interval by +/- 50%.
402 int rand_sign = base::RandInt(0, 1) * 2 - 1;
403
404 // Truncation is adequate for rounding here.
405 backoff_s = backoff_s +
406 (rand_sign * (last_delay.InSeconds() / kBackoffRandomizationFactor));
407
408 // Cap the backoff interval.
409 backoff_s = std::max(1LL, std::min(backoff_s, kMaxBackoffSeconds));
410
411 return TimeDelta::FromSeconds(backoff_s);
412 }
413
414 void SyncerThread::Stop() {
415 syncer_->RequestEarlyExit(); // Safe to call from any thread.
416 thread_.Stop();
417 Notify(SyncEngineEvent::SYNCER_THREAD_EXITING);
418 }
419
420 void SyncerThread::DoCanaryJob() {
421 DCHECK(pending_nudge_.get());
422 wait_interval_->had_nudge = false;
423 SyncSessionJob copy = {pending_nudge_->purpose,
424 pending_nudge_->scheduled_start,
425 pending_nudge_->session};
426 DoSyncSessionJob(copy);
427 }
428
429 void SyncerThread::PollTimerCallback() {
430 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
431 ModelSafeRoutingInfo r;
432 std::vector<ModelSafeWorker*> w;
433 session_context_->registrar()->GetModelSafeRoutingInfo(&r);
434 session_context_->registrar()->GetWorkers(&w);
435 SyncSourceInfo info(GetUpdatesCallerInfo::PERIODIC, ModelTypeBitSet());
436 SyncSession* s = new SyncSession(session_context_.get(), this, info, r, w);
437 ScheduleSyncSessionJob(TimeDelta::FromSeconds(0), SyncSessionJob::POLL, s);
438 }
439
440 void SyncerThread::Unthrottle() {
441 DCHECK_EQ(WaitInterval::THROTTLED, wait_interval_->mode);
442 wait_interval_.reset();
443 }
444
445 void SyncerThread::Notify(SyncEngineEvent::EventCause cause) {
446 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
447 session_context_->NotifyListeners(SyncEngineEvent(cause));
448 }
449
450 bool SyncerThread::IsBackingOff() const {
451 return wait_interval_.get() && wait_interval_->mode ==
452 WaitInterval::EXPONENTIAL_BACKOFF;
453 }
454
455 void SyncerThread::OnSilencedUntil(const base::TimeTicks& silenced_until) {
456 wait_interval_.reset(new WaitInterval(WaitInterval::THROTTLED,
457 silenced_until - TimeTicks::Now()));
458 wait_interval_->timer.Start(wait_interval_->length, this,
459 &SyncerThread::Unthrottle);
460 }
461
462 bool SyncerThread::IsSyncingCurrentlySilenced() {
463 return wait_interval_.get() && wait_interval_->mode ==
464 WaitInterval::THROTTLED;
465 }
466
467 void SyncerThread::OnReceivedShortPollIntervalUpdate(
468 const base::TimeDelta& new_interval) {
469 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
470 syncer_short_poll_interval_seconds_ = new_interval;
471 }
472
473 void SyncerThread::OnReceivedLongPollIntervalUpdate(
474 const base::TimeDelta& new_interval) {
475 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
476 syncer_long_poll_interval_seconds_ = new_interval;
477 }
478
479 void SyncerThread::OnShouldStopSyncingPermanently() {
480 syncer_->RequestEarlyExit(); // Thread-safe.
481 Notify(SyncEngineEvent::STOP_SYNCING_PERMANENTLY);
482 }
483
484 void SyncerThread::OnServerConnectionEvent(
485 const ServerConnectionEvent& event) {
486 NOTIMPLEMENTED();
487 }
488
489 void SyncerThread::set_notifications_enabled(bool notifications_enabled) {
490 session_context_->set_notifications_enabled(notifications_enabled);
491 }
492
493 } // s3
494 } // browser_sync
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698