blob: 900c424b8ee5eea26f5e4e02ecaa4c524a04b0a2 [file] [log] [blame]
akmhoque66e66182014-02-21 17:56:03 -06001/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2012 University of California, Los Angeles
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
19 * Chaoyi Bian <bcy@pku.edu.cn>
akmhoque157b0a42014-05-13 00:26:37 -050020 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
akmhoque66e66182014-02-21 17:56:03 -060021 * Yingdi Yu <yingdi@cs.ucla.edu>
22 */
23
24#include "sync-logic.h"
25#include "sync-diff-leaf.h"
26#include "sync-full-leaf.h"
27#include "sync-logging.h"
28#include "sync-state.h"
29
30#include <boost/foreach.hpp>
31#include <boost/lexical_cast.hpp>
Alexander Afanasyevf9f39102015-12-01 17:43:40 -080032#include <boost/thread.hpp>
akmhoque66e66182014-02-21 17:56:03 -060033#include <vector>
34
35using namespace std;
Vince Lehman0a7da612014-10-29 14:39:29 -050036
37using ndn::Data;
38using ndn::EventId;
39using ndn::KeyChain;
40using ndn::Face;
41using ndn::Name;
42using ndn::OnDataValidated;
43using ndn::OnDataValidationFailed;
44using ndn::Validator;
akmhoque66e66182014-02-21 17:56:03 -060045
46INIT_LOGGER ("SyncLogic");
47
48
49#ifdef _DEBUG
50#define _LOG_DEBUG_ID(v) _LOG_DEBUG(m_instanceId << " " << v)
51#else
52#define _LOG_DEBUG_ID(v) _LOG_DEBUG(v)
53#endif
54
55#define GET_RANDOM(var) var ()
56
57#define TIME_SECONDS_WITH_JITTER(sec) \
akmhoque157b0a42014-05-13 00:26:37 -050058 (ndn::time::seconds(sec) + ndn::time::milliseconds(GET_RANDOM (m_reexpressionJitter)))
akmhoque66e66182014-02-21 17:56:03 -060059
60#define TIME_MILLISECONDS_WITH_JITTER(ms) \
akmhoque157b0a42014-05-13 00:26:37 -050061 (ndn::time::seconds(ms) + ndn::time::milliseconds(GET_RANDOM (m_reexpressionJitter)))
akmhoque66e66182014-02-21 17:56:03 -060062
63namespace Sync {
64
65using ndn::shared_ptr;
66
67int SyncLogic::m_instanceCounter = 0;
68
Yingdi Yu40cd1c32014-04-17 15:02:17 -070069const int SyncLogic::m_syncResponseFreshness = 1000; // MUST BE dividable by 1000!!!
70const int SyncLogic::m_syncInterestReexpress = 4; // seconds
71
akmhoque66e66182014-02-21 17:56:03 -060072SyncLogic::SyncLogic (const Name& syncPrefix,
Yingdi Yu40cd1c32014-04-17 15:02:17 -070073 shared_ptr<Validator> validator,
akmhoque66e66182014-02-21 17:56:03 -060074 shared_ptr<Face> face,
75 LogicUpdateCallback onUpdate,
76 LogicRemoveCallback onRemove)
77 : m_state (new FullState)
akmhoque157b0a42014-05-13 00:26:37 -050078 , m_syncInterestTable (face->getIoService(), ndn::time::seconds(m_syncInterestReexpress))
akmhoque66e66182014-02-21 17:56:03 -060079 , m_syncPrefix (syncPrefix)
80 , m_onUpdate (onUpdate)
81 , m_onRemove (onRemove)
82 , m_perBranch (false)
83 , m_validator(validator)
84 , m_keyChain(new KeyChain())
85 , m_face(face)
akmhoque157b0a42014-05-13 00:26:37 -050086 , m_scheduler(face->getIoService())
akmhoque66e66182014-02-21 17:56:03 -060087 , m_randomGenerator (static_cast<unsigned int> (std::time (0)))
88 , m_rangeUniformRandom (m_randomGenerator, boost::uniform_int<> (200,1000))
89 , m_reexpressionJitter (m_randomGenerator, boost::uniform_int<> (100,500))
90 , m_recoveryRetransmissionInterval (m_defaultRecoveryRetransmitInterval)
Yingdi Yu40cd1c32014-04-17 15:02:17 -070091{
92 m_syncRegisteredPrefixId = m_face->setInterestFilter (m_syncPrefix,
akmhoque157b0a42014-05-13 00:26:37 -050093 bind(&SyncLogic::onSyncInterest,
94 this, _1, _2),
95 bind(&SyncLogic::onSyncRegisterSucceed,
96 this, _1),
97 bind(&SyncLogic::onSyncRegisterFailed,
98 this, _1, _2));
Yingdi Yu40cd1c32014-04-17 15:02:17 -070099
akmhoque66e66182014-02-21 17:56:03 -0600100
akmhoque157b0a42014-05-13 00:26:37 -0500101 m_reexpressingInterestId = m_scheduler.scheduleEvent (ndn::time::seconds (0),
akmhoque66e66182014-02-21 17:56:03 -0600102 bind (&SyncLogic::sendSyncInterest, this));
103
104 m_instanceId = string("Instance " + boost::lexical_cast<string>(m_instanceCounter++) + " ");
105}
106
107SyncLogic::SyncLogic (const Name& syncPrefix,
108 shared_ptr<Validator> validator,
109 shared_ptr<Face> face,
110 LogicPerBranchCallback onUpdateBranch)
111 : m_state (new FullState)
akmhoque157b0a42014-05-13 00:26:37 -0500112 , m_syncInterestTable (face->getIoService(), ndn::time::seconds (m_syncInterestReexpress))
akmhoque66e66182014-02-21 17:56:03 -0600113 , m_syncPrefix (syncPrefix)
114 , m_onUpdateBranch (onUpdateBranch)
115 , m_perBranch(true)
116 , m_validator(validator)
117 , m_keyChain(new KeyChain())
118 , m_face(face)
akmhoque157b0a42014-05-13 00:26:37 -0500119 , m_scheduler(face->getIoService())
akmhoque66e66182014-02-21 17:56:03 -0600120 , m_randomGenerator (static_cast<unsigned int> (std::time (0)))
121 , m_rangeUniformRandom (m_randomGenerator, boost::uniform_int<> (200,1000))
122 , m_reexpressionJitter (m_randomGenerator, boost::uniform_int<> (100,500))
123 , m_recoveryRetransmissionInterval (m_defaultRecoveryRetransmitInterval)
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700124{
125 m_syncRegisteredPrefixId = m_face->setInterestFilter (m_syncPrefix,
akmhoque157b0a42014-05-13 00:26:37 -0500126 bind(&SyncLogic::onSyncInterest,
127 this, _1, _2),
128 bind(&SyncLogic::onSyncRegisterSucceed,
129 this, _1),
130 bind(&SyncLogic::onSyncRegisterFailed,
131 this, _1, _2));
akmhoque66e66182014-02-21 17:56:03 -0600132
akmhoque157b0a42014-05-13 00:26:37 -0500133 m_reexpressingInterestId = m_scheduler.scheduleEvent (ndn::time::seconds (0),
akmhoque66e66182014-02-21 17:56:03 -0600134 bind (&SyncLogic::sendSyncInterest, this));
135}
136
137SyncLogic::~SyncLogic ()
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700138{
139 m_face->unsetInterestFilter(m_syncRegisteredPrefixId);
akmhoque66e66182014-02-21 17:56:03 -0600140 m_scheduler.cancelEvent (m_reexpressingInterestId);
141 m_scheduler.cancelEvent (m_delayedInterestProcessingId);
142}
143
144/**
145 * Two types of intersts
146 *
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700147 * Normal name: .../<hash>
akmhoque66e66182014-02-21 17:56:03 -0600148 * Recovery name: .../recovery/<hash>
149 */
Vince Lehman0a7da612014-10-29 14:39:29 -0500150tuple<DigestConstPtr, std::string>
akmhoque66e66182014-02-21 17:56:03 -0600151SyncLogic::convertNameToDigestAndType (const Name &name)
152{
153 BOOST_ASSERT (m_syncPrefix.isPrefixOf(name));
154
155 int nameLengthDiff = name.size() - m_syncPrefix.size();
156 BOOST_ASSERT (nameLengthDiff > 0);
157 BOOST_ASSERT (nameLengthDiff < 3);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700158
akmhoque157b0a42014-05-13 00:26:37 -0500159 string hash = name.get(-1).toUri();
akmhoque66e66182014-02-21 17:56:03 -0600160 string interestType;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700161
akmhoque66e66182014-02-21 17:56:03 -0600162 if(nameLengthDiff == 1)
163 interestType = "normal";
164 else
akmhoque157b0a42014-05-13 00:26:37 -0500165 interestType = name.get(-2).toUri();
akmhoque66e66182014-02-21 17:56:03 -0600166
167 _LOG_DEBUG_ID (hash << ", " << interestType);
168
Vince Lehman0a7da612014-10-29 14:39:29 -0500169 DigestPtr digest = make_shared<Digest> ();
akmhoque66e66182014-02-21 17:56:03 -0600170 istringstream is (hash);
171 is >> *digest;
172
Vince Lehman0a7da612014-10-29 14:39:29 -0500173 return make_tuple(digest, interestType);
akmhoque66e66182014-02-21 17:56:03 -0600174}
175
176void
177SyncLogic::onSyncInterest (const Name& prefix, const ndn::Interest& interest)
178{
179 Name name = interest.getName();
180
181 _LOG_DEBUG_ID("respondSyncInterest: " << name);
182
183 try
184 {
185 _LOG_DEBUG_ID ("<< I " << name);
186
187 DigestConstPtr digest;
188 string type;
189 tie (digest, type) = convertNameToDigestAndType (name);
190
191 if (type == "normal") // kind of ineffective...
192 {
193 processSyncInterest (name, digest);
194 }
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700195 else if (type == "recovery")
akmhoque66e66182014-02-21 17:56:03 -0600196 {
197 processSyncRecoveryInterest (name, digest);
198 }
199 }
200 catch (Error::DigestCalculationError &e)
201 {
202 _LOG_DEBUG_ID ("Something fishy happened...");
203 // log error. ignoring it for now, later we should log it
204 return ;
205 }
206}
207
208void
akmhoque157b0a42014-05-13 00:26:37 -0500209SyncLogic::onSyncRegisterSucceed(const Name& prefix)
210{
211 _LOG_DEBUG_ID("Sync prefix registration succeeded! " << prefix);
212}
213
214void
akmhoque66e66182014-02-21 17:56:03 -0600215SyncLogic::onSyncRegisterFailed(const Name& prefix, const string& msg)
216{
217 _LOG_DEBUG_ID("Sync prefix registration failed! " << msg);
218}
219
220void
221SyncLogic::onSyncData(const ndn::Interest& interest, Data& data)
222{
223 OnDataValidated onValidated = bind(&SyncLogic::onSyncDataValidated, this, _1);
224 OnDataValidationFailed onValidationFailed = bind(&SyncLogic::onSyncDataValidationFailed, this, _1);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700225 m_validator->validate(data, onValidated, onValidationFailed);
akmhoque66e66182014-02-21 17:56:03 -0600226}
227
228void
229SyncLogic::onSyncTimeout(const ndn::Interest& interest)
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700230{
231 // It is OK. Others will handle the time out situation.
akmhoque66e66182014-02-21 17:56:03 -0600232}
233
234void
235SyncLogic::onSyncDataValidationFailed(const shared_ptr<const Data>& data)
236{
237 _LOG_DEBUG_ID("Sync data cannot be verified!");
238}
239
240void
241SyncLogic::onSyncDataValidated(const shared_ptr<const Data>& data)
242{
243 Name name = data->getName();
244 const char* wireData = (const char*)data->getContent().value();
245 size_t len = data->getContent().value_size();
246
247 try
248 {
249 _LOG_DEBUG_ID ("<< D " << name);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700250
akmhoque66e66182014-02-21 17:56:03 -0600251 DigestConstPtr digest;
252 string type;
253 tie (digest, type) = convertNameToDigestAndType (name);
254
255 if (type == "normal")
256 {
257 processSyncData (name, digest, wireData, len);
258 }
259 else
260 {
261 // timer is always restarted when we schedule recovery
262 m_scheduler.cancelEvent (m_reexpressingRecoveryInterestId);
263 processSyncData (name, digest, wireData, len);
264 }
265 }
266 catch (Error::DigestCalculationError &e)
267 {
268 _LOG_DEBUG_ID ("Something fishy happened...");
269 // log error. ignoring it for now, later we should log it
270 return;
271 }
272}
273
274void
akmhoque157b0a42014-05-13 00:26:37 -0500275SyncLogic::processSyncInterest (const Name &name, DigestConstPtr digest,
276 bool timedProcessing/*=false*/)
akmhoque66e66182014-02-21 17:56:03 -0600277{
278 _LOG_DEBUG_ID("processSyncInterest");
279 DigestConstPtr rootDigest;
280 {
281 rootDigest = m_state->getDigest();
282 }
283
284 // Special case when state is not empty and we have received request with zero-root digest
285 if (digest->isZero () && !rootDigest->isZero ())
286 {
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700287
akmhoque66e66182014-02-21 17:56:03 -0600288 SyncStateMsg ssm;
289 {
290 ssm << (*m_state);
291 }
292 sendSyncData (name, digest, ssm);
293 return;
294 }
295
296 if (*rootDigest == *digest)
297 {
298 _LOG_DEBUG_ID ("processSyncInterest (): Same state. Adding to PIT");
299 m_syncInterestTable.insert (digest, name.toUri(), false);
300 return;
301 }
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700302
akmhoque66e66182014-02-21 17:56:03 -0600303 DiffStateContainer::iterator stateInDiffLog = m_log.find (digest);
304
305 if (stateInDiffLog != m_log.end ())
306 {
307 DiffStateConstPtr stateDiff = (*stateInDiffLog)->diff ();
308
309 sendSyncData (name, digest, stateDiff);
310 return;
311 }
312
313 if (!timedProcessing)
314 {
315 bool exists = m_syncInterestTable.insert (digest, name.toUri(), true);
316 if (exists) // somebody else replied, so restart random-game timer
317 {
akmhoque157b0a42014-05-13 00:26:37 -0500318 _LOG_DEBUG_ID("Unknown digest, but somebody may have already replied, " <<
319 "so restart our timer");
akmhoque66e66182014-02-21 17:56:03 -0600320 m_scheduler.cancelEvent (m_delayedInterestProcessingId);
321 }
322
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700323 uint32_t waitDelay = GET_RANDOM (m_rangeUniformRandom);
akmhoque157b0a42014-05-13 00:26:37 -0500324 _LOG_DEBUG_ID("Digest is not in the log. Schedule processing after small delay: " <<
325 ndn::time::milliseconds (waitDelay));
akmhoque66e66182014-02-21 17:56:03 -0600326
akmhoque157b0a42014-05-13 00:26:37 -0500327 m_delayedInterestProcessingId =
328 m_scheduler.scheduleEvent(ndn::time::milliseconds (waitDelay),
329 bind (&SyncLogic::processSyncInterest, this, name, digest, true));
akmhoque66e66182014-02-21 17:56:03 -0600330 }
331 else
332 {
akmhoque157b0a42014-05-13 00:26:37 -0500333 _LOG_DEBUG_ID(" (timed processing)");
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700334
akmhoque66e66182014-02-21 17:56:03 -0600335 m_recoveryRetransmissionInterval = m_defaultRecoveryRetransmitInterval;
336 sendSyncRecoveryInterests (digest);
337 }
338}
339
340void
akmhoque157b0a42014-05-13 00:26:37 -0500341SyncLogic::processSyncData (const Name &name, DigestConstPtr digest,
342 const char *wireData, size_t len)
akmhoque66e66182014-02-21 17:56:03 -0600343{
Vince Lehman0a7da612014-10-29 14:39:29 -0500344 DiffStatePtr diffLog = make_shared<DiffState> ();
akmhoque66e66182014-02-21 17:56:03 -0600345 bool ownInterestSatisfied = false;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700346
akmhoque66e66182014-02-21 17:56:03 -0600347 try
348 {
349
350 m_syncInterestTable.remove (name.toUri()); // Remove satisfied interest from PIT
351
352 ownInterestSatisfied = (name == m_outstandingInterestName);
353
354 DiffState diff;
355 SyncStateMsg msg;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700356 if (!msg.ParseFromArray(wireData, len) || !msg.IsInitialized())
akmhoque66e66182014-02-21 17:56:03 -0600357 {
358 //Throw
359 BOOST_THROW_EXCEPTION (Error::SyncStateMsgDecodingFailure () );
360 }
361 msg >> diff;
362
363 vector<MissingDataInfo> v;
364 BOOST_FOREACH (LeafConstPtr leaf, diff.getLeaves().get<ordered>())
365 {
Vince Lehman0a7da612014-10-29 14:39:29 -0500366 DiffLeafConstPtr diffLeaf = dynamic_pointer_cast<const DiffLeaf> (leaf);
akmhoque66e66182014-02-21 17:56:03 -0600367 BOOST_ASSERT (diffLeaf != 0);
368
369 NameInfoConstPtr info = diffLeaf->getInfo();
370 if (diffLeaf->getOperation() == UPDATE)
371 {
372 SeqNo seq = diffLeaf->getSeq();
373
374 bool inserted = false;
375 bool updated = false;
376 SeqNo oldSeq;
377 {
Vince Lehman0a7da612014-10-29 14:39:29 -0500378 tie (inserted, updated, oldSeq) = m_state->update (info, seq);
akmhoque66e66182014-02-21 17:56:03 -0600379 }
380
381 if (inserted || updated)
382 {
383 diffLog->update (info, seq);
384 if (!oldSeq.isValid())
385 {
386 oldSeq = SeqNo(seq.getSession(), 0);
387 }
388 else
389 {
390 ++oldSeq;
391 }
392 // there is no need for application to process update on forwarder node
393 if (info->toString() != forwarderPrefix)
394 {
395 MissingDataInfo mdi = {info->toString(), oldSeq, seq};
396 {
397 ostringstream interestName;
akmhoque157b0a42014-05-13 00:26:37 -0500398 interestName << mdi.prefix <<
399 "/" << mdi.high.getSession() <<
400 "/" << mdi.high.getSeq();
akmhoque66e66182014-02-21 17:56:03 -0600401 _LOG_DEBUG_ID("+++++++++++++++ " + interestName.str());
402 }
403 if (m_perBranch)
404 {
405 ostringstream interestName;
akmhoque157b0a42014-05-13 00:26:37 -0500406 interestName << mdi.prefix <<
407 "/" << mdi.high.getSession() <<
408 "/" << mdi.high.getSeq();
akmhoque66e66182014-02-21 17:56:03 -0600409 m_onUpdateBranch(interestName.str());
410 }
411 else
412 {
413 v.push_back(mdi);
414 }
415 }
416 }
417 }
418 else if (diffLeaf->getOperation() == REMOVE)
419 {
420 if (m_state->remove (info))
421 {
422 diffLog->remove (info);
423 if (!m_perBranch)
424 {
425 m_onRemove (info->toString ());
426 }
427 }
428 }
429 else
430 {
431 }
432 }
433
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700434 if (!v.empty())
akmhoque66e66182014-02-21 17:56:03 -0600435 {
436 if (!m_perBranch)
437 {
438 m_onUpdate(v);
439 }
440 }
441
442 insertToDiffLog (diffLog);
443 }
444 catch (Error::SyncStateMsgDecodingFailure &e)
445 {
446 _LOG_DEBUG_ID ("Something really fishy happened during state decoding " <<
447 diagnostic_information (e));
448 diffLog.reset ();
449 // don't do anything
450 }
451
452 if ((diffLog != 0 && diffLog->getLeaves ().size () > 0) ||
453 ownInterestSatisfied)
454 {
455 _LOG_DEBUG_ID(" +++++++++++++++ state changed!!!");
456 // Do it only if everything went fine and state changed
457
458 // this is kind of wrong
akmhoque157b0a42014-05-13 00:26:37 -0500459 // satisfyPendingSyncInterests (diffLog); // if there are interests in PIT,
460 // // there is a point to satisfy them using new state
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700461
akmhoque66e66182014-02-21 17:56:03 -0600462 // if state has changed, then it is safe to express a new interest
akmhoque157b0a42014-05-13 00:26:37 -0500463 ndn::time::system_clock::Duration after =
464 ndn::time::milliseconds(GET_RANDOM (m_reexpressionJitter));
akmhoque66e66182014-02-21 17:56:03 -0600465 // cout << "------------ reexpress interest after: " << after << endl;
466 EventId eventId = m_scheduler.scheduleEvent (after,
467 bind (&SyncLogic::sendSyncInterest, this));
468
469 m_scheduler.cancelEvent (m_reexpressingInterestId);
470 m_reexpressingInterestId = eventId;
471 }
472}
473
474void
475SyncLogic::processSyncRecoveryInterest (const Name &name, DigestConstPtr digest)
476{
477 _LOG_DEBUG_ID("processSyncRecoveryInterest");
478 DiffStateContainer::iterator stateInDiffLog = m_log.find (digest);
479
480 if (stateInDiffLog == m_log.end ())
481 {
482 _LOG_DEBUG_ID ("Could not find " << *digest << " in digest log");
483 return;
484 }
485
486 SyncStateMsg ssm;
487 {
488 ssm << (*m_state);
489 }
490 sendSyncData (name, digest, ssm);
491}
492
493void
494SyncLogic::satisfyPendingSyncInterests (DiffStateConstPtr diffLog)
495{
Vince Lehman0a7da612014-10-29 14:39:29 -0500496 DiffStatePtr fullStateLog = make_shared<DiffState> ();
akmhoque66e66182014-02-21 17:56:03 -0600497 {
498 BOOST_FOREACH (LeafConstPtr leaf, m_state->getLeaves ()/*.get<timed> ()*/)
499 {
500 fullStateLog->update (leaf->getInfo (), leaf->getSeq ());
501 /// @todo Impose limit on how many state info should be send out
502 }
503 }
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700504
akmhoque66e66182014-02-21 17:56:03 -0600505 try
506 {
507 uint32_t counter = 0;
508 while (m_syncInterestTable.size () > 0)
509 {
510 Sync::Interest interest = m_syncInterestTable.pop ();
511
512 if (!interest.m_unknown)
513 {
514 _LOG_DEBUG_ID (">> D " << interest.m_name);
515 sendSyncData (interest.m_name, interest.m_digest, diffLog);
516 }
517 else
518 {
519 _LOG_DEBUG_ID (">> D (unknown)" << interest.m_name);
520 sendSyncData (interest.m_name, interest.m_digest, fullStateLog);
521 }
522 counter ++;
523 }
524 _LOG_DEBUG_ID ("Satisfied " << counter << " pending interests");
525 }
526 catch (Error::InterestTableIsEmpty &e)
527 {
528 // ok. not really an error
529 }
530}
531
532void
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700533SyncLogic::insertToDiffLog (DiffStatePtr diffLog)
akmhoque66e66182014-02-21 17:56:03 -0600534{
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700535 diffLog->setDigest (m_state->getDigest());
akmhoque66e66182014-02-21 17:56:03 -0600536 if (m_log.size () > 0)
537 {
538 m_log.get<sequenced> ().front ()->setNext (diffLog);
539 }
akmhoque157b0a42014-05-13 00:26:37 -0500540 m_log.erase (m_state->getDigest()); // remove diff state with the same digest.
541 // next pointers are still valid
akmhoque66e66182014-02-21 17:56:03 -0600542 /// @todo Optimization
543 m_log.get<sequenced> ().push_front (diffLog);
544}
545
546void
547SyncLogic::addLocalNames (const Name &prefix, uint64_t session, uint64_t seq)
548{
549 DiffStatePtr diff;
550 {
551 //cout << "Add local names" <<endl;
552 NameInfoConstPtr info = StdNameInfo::FindOrCreate(prefix.toUri());
553
554 _LOG_DEBUG_ID ("addLocalNames (): old state " << *m_state->getDigest ());
555
556 SeqNo seqN (session, seq);
557 m_state->update(info, seqN);
558
559 _LOG_DEBUG_ID ("addLocalNames (): new state " << *m_state->getDigest ());
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700560
Vince Lehman0a7da612014-10-29 14:39:29 -0500561 diff = make_shared<DiffState>();
akmhoque66e66182014-02-21 17:56:03 -0600562 diff->update(info, seqN);
563 insertToDiffLog (diff);
564 }
565
566 // _LOG_DEBUG_ID ("PIT size: " << m_syncInterestTable.size ());
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700567 satisfyPendingSyncInterests (diff);
akmhoque66e66182014-02-21 17:56:03 -0600568}
569
570void
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700571SyncLogic::remove(const Name &prefix)
akmhoque66e66182014-02-21 17:56:03 -0600572{
573 DiffStatePtr diff;
574 {
575 NameInfoConstPtr info = StdNameInfo::FindOrCreate(prefix.toUri());
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700576 m_state->remove(info);
akmhoque66e66182014-02-21 17:56:03 -0600577
578 // increment the sequence number for the forwarder node
579 NameInfoConstPtr forwarderInfo = StdNameInfo::FindOrCreate(forwarderPrefix);
580
581 LeafContainer::iterator item = m_state->getLeaves ().find (forwarderInfo);
582 SeqNo seqNo (0);
583 if (item != m_state->getLeaves ().end ())
584 {
585 seqNo = (*item)->getSeq ();
586 ++seqNo;
587 }
588 m_state->update (forwarderInfo, seqNo);
589
Vince Lehman0a7da612014-10-29 14:39:29 -0500590 diff = make_shared<DiffState>();
akmhoque66e66182014-02-21 17:56:03 -0600591 diff->remove(info);
592 diff->update(forwarderInfo, seqNo);
593
594 insertToDiffLog (diff);
595 }
596
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700597 satisfyPendingSyncInterests (diff);
akmhoque66e66182014-02-21 17:56:03 -0600598}
599
600void
601SyncLogic::sendSyncInterest ()
602{
603 _LOG_DEBUG_ID("sendSyncInterest");
604
605 {
606 m_outstandingInterestName = m_syncPrefix;
607 ostringstream os;
608 os << *m_state->getDigest();
609 m_outstandingInterestName.append(os.str());
610 _LOG_DEBUG_ID (">> I " << m_outstandingInterestName);
611 }
612
613 _LOG_DEBUG_ID("sendSyncInterest: " << m_outstandingInterestName);
614
akmhoque157b0a42014-05-13 00:26:37 -0500615 EventId eventId =
616 m_scheduler.scheduleEvent(ndn::time::seconds(m_syncInterestReexpress) +
617 ndn::time::milliseconds(GET_RANDOM(m_reexpressionJitter)),
618 bind (&SyncLogic::sendSyncInterest, this));
akmhoque66e66182014-02-21 17:56:03 -0600619 m_scheduler.cancelEvent (m_reexpressingInterestId);
620 m_reexpressingInterestId = eventId;
621
622 ndn::Interest interest(m_outstandingInterestName);
623 interest.setMustBeFresh(true);
624
625 m_face->expressInterest(interest,
626 bind(&SyncLogic::onSyncData, this, _1, _2),
627 bind(&SyncLogic::onSyncTimeout, this, _1));
628}
629
630void
631SyncLogic::sendSyncRecoveryInterests (DigestConstPtr digest)
632{
633 ostringstream os;
634 os << *digest;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700635
akmhoque66e66182014-02-21 17:56:03 -0600636 Name interestName = m_syncPrefix;
637 interestName.append("recovery").append(os.str());
638
akmhoque157b0a42014-05-13 00:26:37 -0500639 ndn::time::system_clock::Duration nextRetransmission =
640 ndn::time::milliseconds(m_recoveryRetransmissionInterval + GET_RANDOM (m_reexpressionJitter));
akmhoque66e66182014-02-21 17:56:03 -0600641
642 m_recoveryRetransmissionInterval <<= 1;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700643
akmhoque66e66182014-02-21 17:56:03 -0600644 m_scheduler.cancelEvent (m_reexpressingRecoveryInterestId);
645 if (m_recoveryRetransmissionInterval < 100*1000) // <100 seconds
akmhoque157b0a42014-05-13 00:26:37 -0500646 m_reexpressingRecoveryInterestId =
647 m_scheduler.scheduleEvent (nextRetransmission,
648 bind (&SyncLogic::sendSyncRecoveryInterests, this, digest));
akmhoque66e66182014-02-21 17:56:03 -0600649
650 ndn::Interest interest(interestName);
651 interest.setMustBeFresh(true);
652
653 m_face->expressInterest(interest,
654 bind(&SyncLogic::onSyncData, this, _1, _2),
655 bind(&SyncLogic::onSyncTimeout, this, _1));
656}
657
658
659void
660SyncLogic::sendSyncData (const Name &name, DigestConstPtr digest, StateConstPtr state)
661{
662 SyncStateMsg msg;
663 msg << (*state);
664 sendSyncData(name, digest, msg);
665}
666
667// pass in state msg instead of state, so that there is no need to lock the state until
668// this function returns
669void
670SyncLogic::sendSyncData (const Name &name, DigestConstPtr digest, SyncStateMsg &ssm)
671{
672 _LOG_DEBUG_ID (">> D " << name);
673 int size = ssm.ByteSize();
674 char *wireData = new char[size];
675 ssm.SerializeToArray(wireData, size);
676
akmhoque69c9aa92014-07-23 15:15:05 -0500677 //Data syncData(name);
678 ndn::shared_ptr<ndn::Data> syncData = ndn::make_shared<ndn::Data>();
679 syncData->setName(name);
680 syncData->setContent(reinterpret_cast<const uint8_t*>(wireData), size);
681 syncData->setFreshnessPeriod(ndn::time::seconds(m_syncResponseFreshness));
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700682
akmhoque69c9aa92014-07-23 15:15:05 -0500683 m_keyChain->sign(*syncData);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700684
akmhoque69c9aa92014-07-23 15:15:05 -0500685 m_face->put(*syncData);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700686
akmhoque66e66182014-02-21 17:56:03 -0600687 delete []wireData;
688
689 // checking if our own interest got satisfied
690 bool satisfiedOwnInterest = false;
691 {
692 satisfiedOwnInterest = (m_outstandingInterestName == name);
693 }
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700694
akmhoque66e66182014-02-21 17:56:03 -0600695 if (satisfiedOwnInterest)
696 {
697 _LOG_DEBUG_ID ("Satisfied our own Interest. Re-expressing (hopefully with a new digest)");
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700698
akmhoque157b0a42014-05-13 00:26:37 -0500699 ndn::time::system_clock::Duration after =
700 ndn::time::milliseconds(GET_RANDOM(m_reexpressionJitter));
akmhoque66e66182014-02-21 17:56:03 -0600701 // cout << "------------ reexpress interest after: " << after << endl;
702 EventId eventId = m_scheduler.scheduleEvent (after,
703 bind (&SyncLogic::sendSyncInterest, this));
704 m_scheduler.cancelEvent (m_reexpressingInterestId);
705 m_reexpressingInterestId = eventId;
706 }
707}
708
709string
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700710SyncLogic::getRootDigest()
akmhoque66e66182014-02-21 17:56:03 -0600711{
712 ostringstream os;
713 os << *m_state->getDigest();
714 return os.str();
715}
716
717size_t
718SyncLogic::getNumberOfBranches () const
719{
720 return m_state->getLeaves ().size ();
721}
722
723void
724SyncLogic::printState () const
725{
Vince Lehman0a7da612014-10-29 14:39:29 -0500726 BOOST_FOREACH (const shared_ptr<Sync::Leaf> leaf, m_state->getLeaves ())
akmhoque66e66182014-02-21 17:56:03 -0600727 {
728 std::cout << *leaf << std::endl;
729 }
730}
731
732std::map<std::string, bool>
733SyncLogic::getBranchPrefixes() const
734{
735 std::map<std::string, bool> m;
736
Vince Lehman0a7da612014-10-29 14:39:29 -0500737 BOOST_FOREACH (const shared_ptr<Sync::Leaf> leaf, m_state->getLeaves ())
akmhoque66e66182014-02-21 17:56:03 -0600738 {
739 std::string prefix = leaf->getInfo()->toString();
740 // do not return forwarder prefix
741 if (prefix != forwarderPrefix)
742 {
743 m.insert(pair<std::string, bool>(prefix, false));
744 }
745 }
746
747 return m;
748}
749
750}