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

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

Powered by Google App Engine
This is Rietveld 408576698