blob: 3038532f2f5319c0f3240d06b96fdd91982a84bb [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>
20 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
21 * 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>
32#include <vector>
33
34using namespace std;
35using namespace ndn;
36
37INIT_LOGGER ("SyncLogic");
38
39
40#ifdef _DEBUG
41#define _LOG_DEBUG_ID(v) _LOG_DEBUG(m_instanceId << " " << v)
42#else
43#define _LOG_DEBUG_ID(v) _LOG_DEBUG(v)
44#endif
45
46#define GET_RANDOM(var) var ()
47
48#define TIME_SECONDS_WITH_JITTER(sec) \
49 (time::seconds(sec) + time::milliseconds(GET_RANDOM (m_reexpressionJitter)))
50
51#define TIME_MILLISECONDS_WITH_JITTER(ms) \
52 (time::seconds(ms) + time::milliseconds(GET_RANDOM (m_reexpressionJitter)))
53
54namespace Sync {
55
56using ndn::shared_ptr;
57
58int SyncLogic::m_instanceCounter = 0;
59
Yingdi Yu40cd1c32014-04-17 15:02:17 -070060const int SyncLogic::m_syncResponseFreshness = 1000; // MUST BE dividable by 1000!!!
61const int SyncLogic::m_syncInterestReexpress = 4; // seconds
62
akmhoque66e66182014-02-21 17:56:03 -060063SyncLogic::SyncLogic (const Name& syncPrefix,
Yingdi Yu40cd1c32014-04-17 15:02:17 -070064 shared_ptr<Validator> validator,
akmhoque66e66182014-02-21 17:56:03 -060065 shared_ptr<Face> face,
66 LogicUpdateCallback onUpdate,
67 LogicRemoveCallback onRemove)
68 : m_state (new FullState)
69 , m_syncInterestTable (*face->ioService(), time::seconds(m_syncInterestReexpress))
70 , m_syncPrefix (syncPrefix)
71 , m_onUpdate (onUpdate)
72 , m_onRemove (onRemove)
73 , m_perBranch (false)
74 , m_validator(validator)
75 , m_keyChain(new KeyChain())
76 , m_face(face)
77 , m_scheduler(*face->ioService())
78 , m_randomGenerator (static_cast<unsigned int> (std::time (0)))
79 , m_rangeUniformRandom (m_randomGenerator, boost::uniform_int<> (200,1000))
80 , m_reexpressionJitter (m_randomGenerator, boost::uniform_int<> (100,500))
81 , m_recoveryRetransmissionInterval (m_defaultRecoveryRetransmitInterval)
Yingdi Yu40cd1c32014-04-17 15:02:17 -070082{
83 m_syncRegisteredPrefixId = m_face->setInterestFilter (m_syncPrefix,
84 bind(&SyncLogic::onSyncInterest, this, _1, _2),
akmhoque66e66182014-02-21 17:56:03 -060085 bind(&SyncLogic::onSyncRegisterFailed, this, _1, _2));
Yingdi Yu40cd1c32014-04-17 15:02:17 -070086
akmhoque66e66182014-02-21 17:56:03 -060087
88 m_reexpressingInterestId = m_scheduler.scheduleEvent (time::seconds (0), // no need to add jitter
89 bind (&SyncLogic::sendSyncInterest, this));
90
91 m_instanceId = string("Instance " + boost::lexical_cast<string>(m_instanceCounter++) + " ");
92}
93
94SyncLogic::SyncLogic (const Name& syncPrefix,
95 shared_ptr<Validator> validator,
96 shared_ptr<Face> face,
97 LogicPerBranchCallback onUpdateBranch)
98 : m_state (new FullState)
99 , m_syncInterestTable (*face->ioService(), time::seconds (m_syncInterestReexpress))
100 , m_syncPrefix (syncPrefix)
101 , m_onUpdateBranch (onUpdateBranch)
102 , m_perBranch(true)
103 , m_validator(validator)
104 , m_keyChain(new KeyChain())
105 , m_face(face)
106 , m_scheduler(*face->ioService())
107 , m_randomGenerator (static_cast<unsigned int> (std::time (0)))
108 , m_rangeUniformRandom (m_randomGenerator, boost::uniform_int<> (200,1000))
109 , m_reexpressionJitter (m_randomGenerator, boost::uniform_int<> (100,500))
110 , m_recoveryRetransmissionInterval (m_defaultRecoveryRetransmitInterval)
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700111{
112 m_syncRegisteredPrefixId = m_face->setInterestFilter (m_syncPrefix,
113 bind(&SyncLogic::onSyncInterest, this, _1, _2),
akmhoque66e66182014-02-21 17:56:03 -0600114 bind(&SyncLogic::onSyncRegisterFailed, this, _1, _2));
115
116 m_reexpressingInterestId = m_scheduler.scheduleEvent (time::seconds (0), // no need to add jitter
117 bind (&SyncLogic::sendSyncInterest, this));
118}
119
120SyncLogic::~SyncLogic ()
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700121{
122 m_face->unsetInterestFilter(m_syncRegisteredPrefixId);
akmhoque66e66182014-02-21 17:56:03 -0600123 m_scheduler.cancelEvent (m_reexpressingInterestId);
124 m_scheduler.cancelEvent (m_delayedInterestProcessingId);
125}
126
127/**
128 * Two types of intersts
129 *
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700130 * Normal name: .../<hash>
akmhoque66e66182014-02-21 17:56:03 -0600131 * Recovery name: .../recovery/<hash>
132 */
133boost::tuple<DigestConstPtr, std::string>
134SyncLogic::convertNameToDigestAndType (const Name &name)
135{
136 BOOST_ASSERT (m_syncPrefix.isPrefixOf(name));
137
138 int nameLengthDiff = name.size() - m_syncPrefix.size();
139 BOOST_ASSERT (nameLengthDiff > 0);
140 BOOST_ASSERT (nameLengthDiff < 3);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700141
akmhoque66e66182014-02-21 17:56:03 -0600142 string hash = name.get(-1).toEscapedString();
143 string interestType;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700144
akmhoque66e66182014-02-21 17:56:03 -0600145 if(nameLengthDiff == 1)
146 interestType = "normal";
147 else
148 interestType = name.get(-2).toEscapedString();
149
150 _LOG_DEBUG_ID (hash << ", " << interestType);
151
152 DigestPtr digest = boost::make_shared<Digest> ();
153 istringstream is (hash);
154 is >> *digest;
155
156 return make_tuple (digest, interestType);
157}
158
159void
160SyncLogic::onSyncInterest (const Name& prefix, const ndn::Interest& interest)
161{
162 Name name = interest.getName();
163
164 _LOG_DEBUG_ID("respondSyncInterest: " << name);
165
166 try
167 {
168 _LOG_DEBUG_ID ("<< I " << name);
169
170 DigestConstPtr digest;
171 string type;
172 tie (digest, type) = convertNameToDigestAndType (name);
173
174 if (type == "normal") // kind of ineffective...
175 {
176 processSyncInterest (name, digest);
177 }
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700178 else if (type == "recovery")
akmhoque66e66182014-02-21 17:56:03 -0600179 {
180 processSyncRecoveryInterest (name, digest);
181 }
182 }
183 catch (Error::DigestCalculationError &e)
184 {
185 _LOG_DEBUG_ID ("Something fishy happened...");
186 // log error. ignoring it for now, later we should log it
187 return ;
188 }
189}
190
191void
192SyncLogic::onSyncRegisterFailed(const Name& prefix, const string& msg)
193{
194 _LOG_DEBUG_ID("Sync prefix registration failed! " << msg);
195}
196
197void
198SyncLogic::onSyncData(const ndn::Interest& interest, Data& data)
199{
200 OnDataValidated onValidated = bind(&SyncLogic::onSyncDataValidated, this, _1);
201 OnDataValidationFailed onValidationFailed = bind(&SyncLogic::onSyncDataValidationFailed, this, _1);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700202 m_validator->validate(data, onValidated, onValidationFailed);
akmhoque66e66182014-02-21 17:56:03 -0600203}
204
205void
206SyncLogic::onSyncTimeout(const ndn::Interest& interest)
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700207{
208 // It is OK. Others will handle the time out situation.
akmhoque66e66182014-02-21 17:56:03 -0600209}
210
211void
212SyncLogic::onSyncDataValidationFailed(const shared_ptr<const Data>& data)
213{
214 _LOG_DEBUG_ID("Sync data cannot be verified!");
215}
216
217void
218SyncLogic::onSyncDataValidated(const shared_ptr<const Data>& data)
219{
220 Name name = data->getName();
221 const char* wireData = (const char*)data->getContent().value();
222 size_t len = data->getContent().value_size();
223
224 try
225 {
226 _LOG_DEBUG_ID ("<< D " << name);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700227
akmhoque66e66182014-02-21 17:56:03 -0600228 DigestConstPtr digest;
229 string type;
230 tie (digest, type) = convertNameToDigestAndType (name);
231
232 if (type == "normal")
233 {
234 processSyncData (name, digest, wireData, len);
235 }
236 else
237 {
238 // timer is always restarted when we schedule recovery
239 m_scheduler.cancelEvent (m_reexpressingRecoveryInterestId);
240 processSyncData (name, digest, wireData, len);
241 }
242 }
243 catch (Error::DigestCalculationError &e)
244 {
245 _LOG_DEBUG_ID ("Something fishy happened...");
246 // log error. ignoring it for now, later we should log it
247 return;
248 }
249}
250
251void
252SyncLogic::processSyncInterest (const Name &name, DigestConstPtr digest, bool timedProcessing/*=false*/)
253{
254 _LOG_DEBUG_ID("processSyncInterest");
255 DigestConstPtr rootDigest;
256 {
257 rootDigest = m_state->getDigest();
258 }
259
260 // Special case when state is not empty and we have received request with zero-root digest
261 if (digest->isZero () && !rootDigest->isZero ())
262 {
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700263
akmhoque66e66182014-02-21 17:56:03 -0600264 SyncStateMsg ssm;
265 {
266 ssm << (*m_state);
267 }
268 sendSyncData (name, digest, ssm);
269 return;
270 }
271
272 if (*rootDigest == *digest)
273 {
274 _LOG_DEBUG_ID ("processSyncInterest (): Same state. Adding to PIT");
275 m_syncInterestTable.insert (digest, name.toUri(), false);
276 return;
277 }
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700278
akmhoque66e66182014-02-21 17:56:03 -0600279 DiffStateContainer::iterator stateInDiffLog = m_log.find (digest);
280
281 if (stateInDiffLog != m_log.end ())
282 {
283 DiffStateConstPtr stateDiff = (*stateInDiffLog)->diff ();
284
285 sendSyncData (name, digest, stateDiff);
286 return;
287 }
288
289 if (!timedProcessing)
290 {
291 bool exists = m_syncInterestTable.insert (digest, name.toUri(), true);
292 if (exists) // somebody else replied, so restart random-game timer
293 {
294 _LOG_DEBUG_ID ("Unknown digest, but somebody may have already replied, so restart our timer");
295 m_scheduler.cancelEvent (m_delayedInterestProcessingId);
296 }
297
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700298 uint32_t waitDelay = GET_RANDOM (m_rangeUniformRandom);
akmhoque66e66182014-02-21 17:56:03 -0600299 _LOG_DEBUG_ID ("Digest is not in the log. Schedule processing after small delay: " << time::milliseconds (waitDelay));
300
301 m_delayedInterestProcessingId = m_scheduler.scheduleEvent (time::milliseconds (waitDelay),
302 bind (&SyncLogic::processSyncInterest, this, name, digest, true));
303 }
304 else
305 {
306 _LOG_DEBUG_ID (" (timed processing)");
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700307
akmhoque66e66182014-02-21 17:56:03 -0600308 m_recoveryRetransmissionInterval = m_defaultRecoveryRetransmitInterval;
309 sendSyncRecoveryInterests (digest);
310 }
311}
312
313void
314SyncLogic::processSyncData (const Name &name, DigestConstPtr digest, const char *wireData, size_t len)
315{
316 DiffStatePtr diffLog = boost::make_shared<DiffState> ();
317 bool ownInterestSatisfied = false;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700318
akmhoque66e66182014-02-21 17:56:03 -0600319 try
320 {
321
322 m_syncInterestTable.remove (name.toUri()); // Remove satisfied interest from PIT
323
324 ownInterestSatisfied = (name == m_outstandingInterestName);
325
326 DiffState diff;
327 SyncStateMsg msg;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700328 if (!msg.ParseFromArray(wireData, len) || !msg.IsInitialized())
akmhoque66e66182014-02-21 17:56:03 -0600329 {
330 //Throw
331 BOOST_THROW_EXCEPTION (Error::SyncStateMsgDecodingFailure () );
332 }
333 msg >> diff;
334
335 vector<MissingDataInfo> v;
336 BOOST_FOREACH (LeafConstPtr leaf, diff.getLeaves().get<ordered>())
337 {
338 DiffLeafConstPtr diffLeaf = boost::dynamic_pointer_cast<const DiffLeaf> (leaf);
339 BOOST_ASSERT (diffLeaf != 0);
340
341 NameInfoConstPtr info = diffLeaf->getInfo();
342 if (diffLeaf->getOperation() == UPDATE)
343 {
344 SeqNo seq = diffLeaf->getSeq();
345
346 bool inserted = false;
347 bool updated = false;
348 SeqNo oldSeq;
349 {
350 boost::tie (inserted, updated, oldSeq) = m_state->update (info, seq);
351 }
352
353 if (inserted || updated)
354 {
355 diffLog->update (info, seq);
356 if (!oldSeq.isValid())
357 {
358 oldSeq = SeqNo(seq.getSession(), 0);
359 }
360 else
361 {
362 ++oldSeq;
363 }
364 // there is no need for application to process update on forwarder node
365 if (info->toString() != forwarderPrefix)
366 {
367 MissingDataInfo mdi = {info->toString(), oldSeq, seq};
368 {
369 ostringstream interestName;
370 interestName << mdi.prefix << "/" << mdi.high.getSession() << "/" << mdi.high.getSeq();
371 _LOG_DEBUG_ID("+++++++++++++++ " + interestName.str());
372 }
373 if (m_perBranch)
374 {
375 ostringstream interestName;
376 interestName << mdi.prefix << "/" << mdi.high.getSession() << "/" << mdi.high.getSeq();
377 m_onUpdateBranch(interestName.str());
378 }
379 else
380 {
381 v.push_back(mdi);
382 }
383 }
384 }
385 }
386 else if (diffLeaf->getOperation() == REMOVE)
387 {
388 if (m_state->remove (info))
389 {
390 diffLog->remove (info);
391 if (!m_perBranch)
392 {
393 m_onRemove (info->toString ());
394 }
395 }
396 }
397 else
398 {
399 }
400 }
401
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700402 if (!v.empty())
akmhoque66e66182014-02-21 17:56:03 -0600403 {
404 if (!m_perBranch)
405 {
406 m_onUpdate(v);
407 }
408 }
409
410 insertToDiffLog (diffLog);
411 }
412 catch (Error::SyncStateMsgDecodingFailure &e)
413 {
414 _LOG_DEBUG_ID ("Something really fishy happened during state decoding " <<
415 diagnostic_information (e));
416 diffLog.reset ();
417 // don't do anything
418 }
419
420 if ((diffLog != 0 && diffLog->getLeaves ().size () > 0) ||
421 ownInterestSatisfied)
422 {
423 _LOG_DEBUG_ID(" +++++++++++++++ state changed!!!");
424 // Do it only if everything went fine and state changed
425
426 // this is kind of wrong
427 // satisfyPendingSyncInterests (diffLog); // if there are interests in PIT, there is a point to satisfy them using new state
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700428
akmhoque66e66182014-02-21 17:56:03 -0600429 // if state has changed, then it is safe to express a new interest
akmhoque05d5fcf2014-04-15 14:58:45 -0500430 time::system_clock::Duration after = time::milliseconds(GET_RANDOM (m_reexpressionJitter));
akmhoque66e66182014-02-21 17:56:03 -0600431 // cout << "------------ reexpress interest after: " << after << endl;
432 EventId eventId = m_scheduler.scheduleEvent (after,
433 bind (&SyncLogic::sendSyncInterest, this));
434
435 m_scheduler.cancelEvent (m_reexpressingInterestId);
436 m_reexpressingInterestId = eventId;
437 }
438}
439
440void
441SyncLogic::processSyncRecoveryInterest (const Name &name, DigestConstPtr digest)
442{
443 _LOG_DEBUG_ID("processSyncRecoveryInterest");
444 DiffStateContainer::iterator stateInDiffLog = m_log.find (digest);
445
446 if (stateInDiffLog == m_log.end ())
447 {
448 _LOG_DEBUG_ID ("Could not find " << *digest << " in digest log");
449 return;
450 }
451
452 SyncStateMsg ssm;
453 {
454 ssm << (*m_state);
455 }
456 sendSyncData (name, digest, ssm);
457}
458
459void
460SyncLogic::satisfyPendingSyncInterests (DiffStateConstPtr diffLog)
461{
462 DiffStatePtr fullStateLog = boost::make_shared<DiffState> ();
463 {
464 BOOST_FOREACH (LeafConstPtr leaf, m_state->getLeaves ()/*.get<timed> ()*/)
465 {
466 fullStateLog->update (leaf->getInfo (), leaf->getSeq ());
467 /// @todo Impose limit on how many state info should be send out
468 }
469 }
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700470
akmhoque66e66182014-02-21 17:56:03 -0600471 try
472 {
473 uint32_t counter = 0;
474 while (m_syncInterestTable.size () > 0)
475 {
476 Sync::Interest interest = m_syncInterestTable.pop ();
477
478 if (!interest.m_unknown)
479 {
480 _LOG_DEBUG_ID (">> D " << interest.m_name);
481 sendSyncData (interest.m_name, interest.m_digest, diffLog);
482 }
483 else
484 {
485 _LOG_DEBUG_ID (">> D (unknown)" << interest.m_name);
486 sendSyncData (interest.m_name, interest.m_digest, fullStateLog);
487 }
488 counter ++;
489 }
490 _LOG_DEBUG_ID ("Satisfied " << counter << " pending interests");
491 }
492 catch (Error::InterestTableIsEmpty &e)
493 {
494 // ok. not really an error
495 }
496}
497
498void
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700499SyncLogic::insertToDiffLog (DiffStatePtr diffLog)
akmhoque66e66182014-02-21 17:56:03 -0600500{
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700501 diffLog->setDigest (m_state->getDigest());
akmhoque66e66182014-02-21 17:56:03 -0600502 if (m_log.size () > 0)
503 {
504 m_log.get<sequenced> ().front ()->setNext (diffLog);
505 }
506 m_log.erase (m_state->getDigest()); // remove diff state with the same digest. next pointers are still valid
507 /// @todo Optimization
508 m_log.get<sequenced> ().push_front (diffLog);
509}
510
511void
512SyncLogic::addLocalNames (const Name &prefix, uint64_t session, uint64_t seq)
513{
514 DiffStatePtr diff;
515 {
516 //cout << "Add local names" <<endl;
517 NameInfoConstPtr info = StdNameInfo::FindOrCreate(prefix.toUri());
518
519 _LOG_DEBUG_ID ("addLocalNames (): old state " << *m_state->getDigest ());
520
521 SeqNo seqN (session, seq);
522 m_state->update(info, seqN);
523
524 _LOG_DEBUG_ID ("addLocalNames (): new state " << *m_state->getDigest ());
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700525
akmhoque66e66182014-02-21 17:56:03 -0600526 diff = boost::make_shared<DiffState>();
527 diff->update(info, seqN);
528 insertToDiffLog (diff);
529 }
530
531 // _LOG_DEBUG_ID ("PIT size: " << m_syncInterestTable.size ());
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700532 satisfyPendingSyncInterests (diff);
akmhoque66e66182014-02-21 17:56:03 -0600533}
534
535void
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700536SyncLogic::remove(const Name &prefix)
akmhoque66e66182014-02-21 17:56:03 -0600537{
538 DiffStatePtr diff;
539 {
540 NameInfoConstPtr info = StdNameInfo::FindOrCreate(prefix.toUri());
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700541 m_state->remove(info);
akmhoque66e66182014-02-21 17:56:03 -0600542
543 // increment the sequence number for the forwarder node
544 NameInfoConstPtr forwarderInfo = StdNameInfo::FindOrCreate(forwarderPrefix);
545
546 LeafContainer::iterator item = m_state->getLeaves ().find (forwarderInfo);
547 SeqNo seqNo (0);
548 if (item != m_state->getLeaves ().end ())
549 {
550 seqNo = (*item)->getSeq ();
551 ++seqNo;
552 }
553 m_state->update (forwarderInfo, seqNo);
554
555 diff = boost::make_shared<DiffState>();
556 diff->remove(info);
557 diff->update(forwarderInfo, seqNo);
558
559 insertToDiffLog (diff);
560 }
561
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700562 satisfyPendingSyncInterests (diff);
akmhoque66e66182014-02-21 17:56:03 -0600563}
564
565void
566SyncLogic::sendSyncInterest ()
567{
568 _LOG_DEBUG_ID("sendSyncInterest");
569
570 {
571 m_outstandingInterestName = m_syncPrefix;
572 ostringstream os;
573 os << *m_state->getDigest();
574 m_outstandingInterestName.append(os.str());
575 _LOG_DEBUG_ID (">> I " << m_outstandingInterestName);
576 }
577
578 _LOG_DEBUG_ID("sendSyncInterest: " << m_outstandingInterestName);
579
580 EventId eventId = m_scheduler.scheduleEvent (time::seconds(m_syncInterestReexpress) + time::milliseconds(GET_RANDOM (m_reexpressionJitter)),
581 bind (&SyncLogic::sendSyncInterest, this));
582 m_scheduler.cancelEvent (m_reexpressingInterestId);
583 m_reexpressingInterestId = eventId;
584
585 ndn::Interest interest(m_outstandingInterestName);
586 interest.setMustBeFresh(true);
587
588 m_face->expressInterest(interest,
589 bind(&SyncLogic::onSyncData, this, _1, _2),
590 bind(&SyncLogic::onSyncTimeout, this, _1));
591}
592
593void
594SyncLogic::sendSyncRecoveryInterests (DigestConstPtr digest)
595{
596 ostringstream os;
597 os << *digest;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700598
akmhoque66e66182014-02-21 17:56:03 -0600599 Name interestName = m_syncPrefix;
600 interestName.append("recovery").append(os.str());
601
akmhoque05d5fcf2014-04-15 14:58:45 -0500602 time::system_clock::Duration nextRetransmission = time::milliseconds (m_recoveryRetransmissionInterval + GET_RANDOM (m_reexpressionJitter));
akmhoque66e66182014-02-21 17:56:03 -0600603
604 m_recoveryRetransmissionInterval <<= 1;
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700605
akmhoque66e66182014-02-21 17:56:03 -0600606 m_scheduler.cancelEvent (m_reexpressingRecoveryInterestId);
607 if (m_recoveryRetransmissionInterval < 100*1000) // <100 seconds
608 m_reexpressingRecoveryInterestId = m_scheduler.scheduleEvent (nextRetransmission,
609 bind (&SyncLogic::sendSyncRecoveryInterests, this, digest));
610
611 ndn::Interest interest(interestName);
612 interest.setMustBeFresh(true);
613
614 m_face->expressInterest(interest,
615 bind(&SyncLogic::onSyncData, this, _1, _2),
616 bind(&SyncLogic::onSyncTimeout, this, _1));
617}
618
619
620void
621SyncLogic::sendSyncData (const Name &name, DigestConstPtr digest, StateConstPtr state)
622{
623 SyncStateMsg msg;
624 msg << (*state);
625 sendSyncData(name, digest, msg);
626}
627
628// pass in state msg instead of state, so that there is no need to lock the state until
629// this function returns
630void
631SyncLogic::sendSyncData (const Name &name, DigestConstPtr digest, SyncStateMsg &ssm)
632{
633 _LOG_DEBUG_ID (">> D " << name);
634 int size = ssm.ByteSize();
635 char *wireData = new char[size];
636 ssm.SerializeToArray(wireData, size);
637
638 Data syncData(name);
639 syncData.setContent(reinterpret_cast<const uint8_t*>(wireData), size);
akmhoque05d5fcf2014-04-15 14:58:45 -0500640 syncData.setFreshnessPeriod(time::seconds(m_syncResponseFreshness));
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700641
akmhoque66e66182014-02-21 17:56:03 -0600642 m_keyChain->sign(syncData);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700643
akmhoque66e66182014-02-21 17:56:03 -0600644 m_face->put(syncData);
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700645
akmhoque66e66182014-02-21 17:56:03 -0600646 delete []wireData;
647
648 // checking if our own interest got satisfied
649 bool satisfiedOwnInterest = false;
650 {
651 satisfiedOwnInterest = (m_outstandingInterestName == name);
652 }
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700653
akmhoque66e66182014-02-21 17:56:03 -0600654 if (satisfiedOwnInterest)
655 {
656 _LOG_DEBUG_ID ("Satisfied our own Interest. Re-expressing (hopefully with a new digest)");
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700657
akmhoque05d5fcf2014-04-15 14:58:45 -0500658 time::system_clock::Duration after = time::milliseconds(GET_RANDOM (m_reexpressionJitter));
akmhoque66e66182014-02-21 17:56:03 -0600659 // cout << "------------ reexpress interest after: " << after << endl;
660 EventId eventId = m_scheduler.scheduleEvent (after,
661 bind (&SyncLogic::sendSyncInterest, this));
662 m_scheduler.cancelEvent (m_reexpressingInterestId);
663 m_reexpressingInterestId = eventId;
664 }
665}
666
667string
Yingdi Yu40cd1c32014-04-17 15:02:17 -0700668SyncLogic::getRootDigest()
akmhoque66e66182014-02-21 17:56:03 -0600669{
670 ostringstream os;
671 os << *m_state->getDigest();
672 return os.str();
673}
674
675size_t
676SyncLogic::getNumberOfBranches () const
677{
678 return m_state->getLeaves ().size ();
679}
680
681void
682SyncLogic::printState () const
683{
684 BOOST_FOREACH (const boost::shared_ptr<Sync::Leaf> leaf, m_state->getLeaves ())
685 {
686 std::cout << *leaf << std::endl;
687 }
688}
689
690std::map<std::string, bool>
691SyncLogic::getBranchPrefixes() const
692{
693 std::map<std::string, bool> m;
694
695 BOOST_FOREACH (const boost::shared_ptr<Sync::Leaf> leaf, m_state->getLeaves ())
696 {
697 std::string prefix = leaf->getInfo()->toString();
698 // do not return forwarder prefix
699 if (prefix != forwarderPrefix)
700 {
701 m.insert(pair<std::string, bool>(prefix, false));
702 }
703 }
704
705 return m;
706}
707
708}