consumer.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2020, The University of Memphis
4  *
5  * This file is part of PSync.
6  * See AUTHORS.md for complete list of PSync authors and contributors.
7  *
8  * PSync is free software: you can redistribute it and/or modify it under the terms
9  * of the GNU Lesser General Public License as published by the Free Software Foundation,
10  * either version 3 of the License, or (at your option) any later version.
11  *
12  * PSync is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
13  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14  * PURPOSE. See the GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License along with
17  * PSync, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "PSync/consumer.hpp"
21 #include "PSync/detail/state.hpp"
22 
23 #include <ndn-cxx/security/validator-null.hpp>
24 #include <ndn-cxx/util/logger.hpp>
25 
26 namespace psync {
27 
29 
30 Consumer::Consumer(const ndn::Name& syncPrefix,
31  ndn::Face& face,
32  const ReceiveHelloCallback& onReceiveHelloData,
33  const UpdateCallback& onUpdate,
34  unsigned int count,
35  double false_positive = 0.001,
36  ndn::time::milliseconds helloInterestLifetime,
37  ndn::time::milliseconds syncInterestLifetime)
38  : m_face(face)
39  , m_scheduler(m_face.getIoService())
40  , m_syncPrefix(syncPrefix)
41  , m_helloInterestPrefix(ndn::Name(m_syncPrefix).append("hello"))
42  , m_syncInterestPrefix(ndn::Name(m_syncPrefix).append("sync"))
43  , m_syncDataContentType(ndn::tlv::ContentType_Blob)
44  , m_onReceiveHelloData(onReceiveHelloData)
45  , m_onUpdate(onUpdate)
46  , m_bloomFilter(count, false_positive)
47  , m_helloInterestLifetime(helloInterestLifetime)
48  , m_syncInterestLifetime(syncInterestLifetime)
49  , m_rng(ndn::random::getRandomNumberEngine())
50  , m_rangeUniformRandom(100, 500)
51 {
52 }
53 
54 bool
55 Consumer::addSubscription(const ndn::Name& prefix, uint64_t seqNo, bool callSyncDataCb)
56 {
57  auto it = m_prefixes.emplace(prefix, seqNo);
58  if (!it.second) {
59  return false;
60  }
61 
62  m_subscriptionList.emplace(prefix);
63  m_bloomFilter.insert(prefix.toUri());
64 
65  if (callSyncDataCb && seqNo != 0) {
66  m_onUpdate({{prefix, seqNo, seqNo}});
67  }
68 
69  return true;
70 }
71 
72 void
74 {
75  m_scheduler.cancelAllEvents();
76 
77  if (m_syncFetcher) {
78  m_syncFetcher->stop();
79  m_syncFetcher.reset();
80  }
81 
82  if (m_helloFetcher) {
83  m_helloFetcher->stop();
84  m_helloFetcher.reset();
85  }
86 }
87 
88 void
90 {
91  ndn::Interest helloInterest(m_helloInterestPrefix);
92  NDN_LOG_DEBUG("Send Hello Interest " << helloInterest);
93 
94  if (m_helloFetcher) {
95  m_helloFetcher->stop();
96  }
97 
98  using ndn::util::SegmentFetcher;
99  SegmentFetcher::Options options;
100  options.interestLifetime = m_helloInterestLifetime;
101  options.maxTimeout = m_helloInterestLifetime;
102  options.rttOptions.initialRto = m_syncInterestLifetime;
103 
104  m_helloFetcher = SegmentFetcher::start(m_face, helloInterest,
105  ndn::security::getAcceptAllValidator(), options);
106 
107  m_helloFetcher->afterSegmentValidated.connect([this] (const ndn::Data& data) {
108  if (data.getFinalBlock()) {
109  m_helloDataName = data.getName().getPrefix(-2);
110  }
111  });
112 
113  m_helloFetcher->onComplete.connect([this] (const ndn::ConstBufferPtr& bufferPtr) {
114  onHelloData(bufferPtr);
115  });
116 
117  m_helloFetcher->onError.connect([this] (uint32_t errorCode, const std::string& msg) {
118  NDN_LOG_TRACE("Cannot fetch hello data, error: " << errorCode << " message: " << msg);
119  ndn::time::milliseconds after(m_rangeUniformRandom(m_rng));
120  NDN_LOG_TRACE("Scheduling after " << after);
121  m_scheduler.schedule(after, [this] { sendHelloInterest(); });
122  });
123 }
124 
125 void
126 Consumer::onHelloData(const ndn::ConstBufferPtr& bufferPtr)
127 {
128  NDN_LOG_DEBUG("On Hello Data");
129 
130  // Extract IBF from name which is the last element in hello data's name
131  m_iblt = m_helloDataName.getSubName(m_helloDataName.size() - 1, 1);
132 
133  NDN_LOG_TRACE("m_iblt: " << std::hash<std::string>{}(m_iblt.toUri()));
134 
135  detail::State state{ndn::Block(bufferPtr)};
136  std::vector<MissingDataInfo> updates;
137  std::map<ndn::Name, uint64_t> availableSubscriptions;
138 
139  NDN_LOG_DEBUG("Hello Data: " << state);
140 
141  for (const auto& content : state) {
142  const ndn::Name& prefix = content.getPrefix(-1);
143  uint64_t seq = content.get(content.size() - 1).toNumber();
144  // If consumer is subscribed then prefix must already be present in
145  // m_prefixes (see addSubscription). So [] operator is safe to use.
146  if (isSubscribed(prefix) && seq > m_prefixes[prefix]) {
147  // In case we are behind on this prefix and consumer is subscribed to it
148  updates.push_back({prefix, m_prefixes[prefix] + 1, seq});
149  m_prefixes[prefix] = seq;
150  }
151  availableSubscriptions.emplace(prefix, seq);
152  }
153 
154  m_onReceiveHelloData(availableSubscriptions);
155 
156  if (!updates.empty()) {
157  NDN_LOG_DEBUG("Updating application with missed updates");
158  m_onUpdate(updates);
159  }
160 }
161 
162 void
164 {
165  BOOST_ASSERT(!m_iblt.empty());
166 
167  ndn::Name syncInterestName(m_syncInterestPrefix);
168 
169  // Append subscription list
170  m_bloomFilter.appendToName(syncInterestName);
171 
172  // Append IBF received in hello/sync data
173  syncInterestName.append(m_iblt);
174 
175  ndn::Interest syncInterest(syncInterestName);
176 
177  NDN_LOG_DEBUG("sendSyncInterest, nonce: " << syncInterest.getNonce() <<
178  " hash: " << std::hash<std::string>{}(syncInterest.getName().toUri()));
179 
180  if (m_syncFetcher) {
181  m_syncFetcher->stop();
182  }
183 
184  using ndn::util::SegmentFetcher;
185  SegmentFetcher::Options options;
186  options.interestLifetime = m_syncInterestLifetime;
187  options.maxTimeout = m_syncInterestLifetime;
188  options.rttOptions.initialRto = m_syncInterestLifetime;
189 
190  m_syncFetcher = SegmentFetcher::start(m_face, syncInterest,
191  ndn::security::getAcceptAllValidator(), options);
192 
193  m_syncFetcher->afterSegmentValidated.connect([this] (const ndn::Data& data) {
194  if (data.getFinalBlock()) {
195  m_syncDataName = data.getName().getPrefix(-2);
196  m_syncDataContentType = data.getContentType();
197  }
198 
199  if (m_syncDataContentType == ndn::tlv::ContentType_Nack) {
200  NDN_LOG_DEBUG("Received application Nack from producer, sending hello again");
202  }
203  });
204 
205  m_syncFetcher->onComplete.connect([this] (const ndn::ConstBufferPtr& bufferPtr) {
206  if (m_syncDataContentType == ndn::tlv::ContentType_Nack) {
207  m_syncDataContentType = ndn::tlv::ContentType_Blob;
208  return;
209  }
210  NDN_LOG_TRACE("Segment fetcher got sync data");
211  onSyncData(bufferPtr);
212  });
213 
214  m_syncFetcher->onError.connect([this] (uint32_t errorCode, const std::string& msg) {
215  NDN_LOG_TRACE("Cannot fetch sync data, error: " << errorCode << " message: " << msg);
216  if (errorCode == SegmentFetcher::ErrorCode::INTEREST_TIMEOUT) {
218  }
219  else {
220  ndn::time::milliseconds after(m_rangeUniformRandom(m_rng));
221  NDN_LOG_TRACE("Scheduling sync Interest after: " << after);
222  m_scheduler.schedule(after, [this] { sendSyncInterest(); });
223  }
224  });
225 }
226 
227 void
228 Consumer::onSyncData(const ndn::ConstBufferPtr& bufferPtr)
229 {
230  // Extract IBF from sync data name which is the last component
231  m_iblt = m_syncDataName.getSubName(m_syncDataName.size() - 1, 1);
232 
233  detail::State state{ndn::Block(bufferPtr)};
234  std::vector<MissingDataInfo> updates;
235 
236  for (const auto& content : state) {
237  NDN_LOG_DEBUG(content);
238  const ndn::Name& prefix = content.getPrefix(-1);
239  uint64_t seq = content.get(content.size() - 1).toNumber();
240  if (m_prefixes.find(prefix) == m_prefixes.end() || seq > m_prefixes[prefix]) {
241  // If this is just the next seq number then we had already informed the consumer about
242  // the previous sequence number and hence seq low and seq high should be equal to current seq
243  updates.push_back({prefix, m_prefixes[prefix] + 1, seq});
244  m_prefixes[prefix] = seq;
245  }
246  // Else updates will be empty and consumer will not be notified.
247  }
248 
249  NDN_LOG_DEBUG("Sync Data: " << state);
250 
251  if (!updates.empty()) {
252  m_onUpdate(updates);
253  }
254 
256 }
257 
258 } // namespace psync
Consumer logic to subscribe to producer&#39;s data.
Definition: consumer.hpp:61
void insert(const std::string &key)
Definition: common.hpp:33
NDN_LOG_INIT(psync.Consumer)
Consumer(const ndn::Name &syncPrefix, ndn::Face &face, const ReceiveHelloCallback &onReceiveHelloData, const UpdateCallback &onUpdate, unsigned int count, double false_positive, ndn::time::milliseconds helloInterestLifetime=HELLO_INTEREST_LIFETIME, ndn::time::milliseconds syncInterestLifetime=SYNC_INTEREST_LIFETIME)
constructor
Definition: consumer.cpp:30
std::function< void(const std::map< ndn::Name, uint64_t > &)> ReceiveHelloCallback
Definition: consumer.hpp:39
bool isSubscribed(const ndn::Name &prefix) const
Definition: consumer.hpp:123
void sendSyncInterest()
send sync interest /<sync-prefix>/sync/<BF>/<producers-IBF>
Definition: consumer.cpp:163
std::function< void(const std::vector< MissingDataInfo > &)> UpdateCallback
Definition: common.hpp:62
bool addSubscription(const ndn::Name &prefix, uint64_t seqNo, bool callSyncDataCb=true)
Add prefix to subscription list.
Definition: consumer.cpp:55
void stop()
Stop segment fetcher to stop the sync and free resources.
Definition: consumer.cpp:73
void sendHelloInterest()
send hello interest /<sync-prefix>/hello/
Definition: consumer.cpp:89
void appendToName(ndn::Name &name) const
Append our bloom filter to the given name.