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-2022, 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 
28 NDN_LOG_INIT(psync.Consumer);
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  NDN_LOG_DEBUG("Subscribing prefix: " << prefix);
63 
64  m_subscriptionList.emplace(prefix);
65  m_bloomFilter.insert(prefix);
66 
67  if (callSyncDataCb && seqNo != 0) {
68  m_onUpdate({{prefix, seqNo, seqNo, 0}});
69  }
70 
71  return true;
72 }
73 
74 bool
75 Consumer::removeSubscription(const ndn::Name& prefix)
76 {
77  if (!isSubscribed(prefix))
78  return false;
79 
80  NDN_LOG_DEBUG("Unsubscribing prefix: " << prefix);
81 
82  m_prefixes.erase(prefix);
83  m_subscriptionList.erase(prefix);
84 
85  // Clear and reconstruct the bloom filter
86  m_bloomFilter.clear();
87 
88  for (const auto& item : m_subscriptionList)
89  m_bloomFilter.insert(item);
90 
91  return true;
92 }
93 
94 void
96 {
97  NDN_LOG_DEBUG("Canceling all the scheduled events");
98  m_scheduler.cancelAllEvents();
99 
100  if (m_syncFetcher) {
101  m_syncFetcher->stop();
102  m_syncFetcher.reset();
103  }
104 
105  if (m_helloFetcher) {
106  m_helloFetcher->stop();
107  m_helloFetcher.reset();
108  }
109 }
110 
111 void
113 {
114  ndn::Interest helloInterest(m_helloInterestPrefix);
115  NDN_LOG_DEBUG("Send Hello Interest " << helloInterest);
116 
117  if (m_helloFetcher) {
118  m_helloFetcher->stop();
119  }
120 
121  using ndn::util::SegmentFetcher;
122  SegmentFetcher::Options options;
123  options.interestLifetime = m_helloInterestLifetime;
124  options.maxTimeout = m_helloInterestLifetime;
125  options.rttOptions.initialRto = m_syncInterestLifetime;
126 
127  m_helloFetcher = SegmentFetcher::start(m_face, helloInterest,
128  ndn::security::getAcceptAllValidator(), options);
129 
130  m_helloFetcher->afterSegmentValidated.connect([this] (const ndn::Data& data) {
131  if (data.getFinalBlock()) {
132  m_helloDataName = data.getName().getPrefix(-2);
133  }
134  });
135 
136  m_helloFetcher->onComplete.connect([this] (const ndn::ConstBufferPtr& bufferPtr) {
137  onHelloData(bufferPtr);
138  });
139 
140  m_helloFetcher->onError.connect([this] (uint32_t errorCode, const std::string& msg) {
141  NDN_LOG_TRACE("Cannot fetch hello data, error: " << errorCode << " message: " << msg);
142  ndn::time::milliseconds after(m_rangeUniformRandom(m_rng));
143  NDN_LOG_TRACE("Scheduling after " << after);
144  m_scheduler.schedule(after, [this] { sendHelloInterest(); });
145  });
146 }
147 
148 void
149 Consumer::onHelloData(const ndn::ConstBufferPtr& bufferPtr)
150 {
151  NDN_LOG_DEBUG("On Hello Data");
152 
153  // Extract IBF from name which is the last element in hello data's name
154  m_iblt = m_helloDataName.getSubName(m_helloDataName.size() - 1, 1);
155 
156  NDN_LOG_TRACE("m_iblt: " << std::hash<ndn::Name>{}(m_iblt));
157 
158  detail::State state{ndn::Block(bufferPtr)};
159  std::vector<MissingDataInfo> updates;
160  std::map<ndn::Name, uint64_t> availableSubscriptions;
161 
162  NDN_LOG_DEBUG("Hello Data: " << state);
163 
164  for (const auto& content : state) {
165  const ndn::Name& prefix = content.getPrefix(-1);
166  uint64_t seq = content.get(content.size() - 1).toNumber();
167  // If consumer is subscribed then prefix must already be present in
168  // m_prefixes (see addSubscription). So [] operator is safe to use.
169  if (isSubscribed(prefix) && seq > m_prefixes[prefix]) {
170  // In case we are behind on this prefix and consumer is subscribed to it
171  updates.push_back({prefix, m_prefixes[prefix] + 1, seq, 0});
172  m_prefixes[prefix] = seq;
173  }
174  availableSubscriptions.emplace(prefix, seq);
175  }
176 
177  m_onReceiveHelloData(availableSubscriptions);
178 
179  if (!updates.empty()) {
180  NDN_LOG_DEBUG("Updating application with missed updates");
181  m_onUpdate(updates);
182  }
183 }
184 
185 void
187 {
188  BOOST_ASSERT(!m_iblt.empty());
189 
190  ndn::Name syncInterestName(m_syncInterestPrefix);
191 
192  // Append subscription list
193  m_bloomFilter.appendToName(syncInterestName);
194 
195  // Append IBF received in hello/sync data
196  syncInterestName.append(m_iblt);
197 
198  ndn::Interest syncInterest(syncInterestName);
199 
200  NDN_LOG_DEBUG("sendSyncInterest, nonce: " << syncInterest.getNonce() <<
201  " hash: " << std::hash<ndn::Name>{}(syncInterest.getName()));
202 
203  if (m_syncFetcher) {
204  m_syncFetcher->stop();
205  }
206 
207  using ndn::util::SegmentFetcher;
208  SegmentFetcher::Options options;
209  options.interestLifetime = m_syncInterestLifetime;
210  options.maxTimeout = m_syncInterestLifetime;
211  options.rttOptions.initialRto = m_syncInterestLifetime;
212 
213  m_syncFetcher = SegmentFetcher::start(m_face, syncInterest,
214  ndn::security::getAcceptAllValidator(), options);
215 
216  m_syncFetcher->afterSegmentValidated.connect([this] (const ndn::Data& data) {
217  if (data.getFinalBlock()) {
218  m_syncDataName = data.getName().getPrefix(-2);
219  m_syncDataContentType = data.getContentType();
220  }
221 
222  if (m_syncDataContentType == ndn::tlv::ContentType_Nack) {
223  NDN_LOG_DEBUG("Received application Nack from producer, sending hello again");
225  }
226  });
227 
228  m_syncFetcher->onComplete.connect([this] (const ndn::ConstBufferPtr& bufferPtr) {
229  if (m_syncDataContentType == ndn::tlv::ContentType_Nack) {
230  m_syncDataContentType = ndn::tlv::ContentType_Blob;
231  return;
232  }
233  NDN_LOG_TRACE("Segment fetcher got sync data");
234  onSyncData(bufferPtr);
235  });
236 
237  m_syncFetcher->onError.connect([this] (uint32_t errorCode, const std::string& msg) {
238  NDN_LOG_TRACE("Cannot fetch sync data, error: " << errorCode << " message: " << msg);
239  if (errorCode == SegmentFetcher::ErrorCode::INTEREST_TIMEOUT) {
241  }
242  else {
243  ndn::time::milliseconds after(m_rangeUniformRandom(m_rng));
244  NDN_LOG_TRACE("Scheduling sync Interest after: " << after);
245  m_scheduler.schedule(after, [this] { sendSyncInterest(); });
246  }
247  });
248 }
249 
250 void
251 Consumer::onSyncData(const ndn::ConstBufferPtr& bufferPtr)
252 {
253  // Extract IBF from sync data name which is the last component
254  m_iblt = m_syncDataName.getSubName(m_syncDataName.size() - 1, 1);
255 
256  detail::State state{ndn::Block(bufferPtr)};
257  std::vector<MissingDataInfo> updates;
258 
259  for (const auto& content : state) {
260  NDN_LOG_DEBUG(content);
261  const ndn::Name& prefix = content.getPrefix(-1);
262  uint64_t seq = content.get(content.size() - 1).toNumber();
263  if (m_prefixes.find(prefix) == m_prefixes.end() || seq > m_prefixes[prefix]) {
264  // If this is just the next seq number then we had already informed the consumer about
265  // the previous sequence number and hence seq low and seq high should be equal to current seq
266  updates.push_back({prefix, m_prefixes[prefix] + 1, seq, 0});
267  m_prefixes[prefix] = seq;
268  }
269  // Else updates will be empty and consumer will not be notified.
270  }
271 
272  NDN_LOG_DEBUG("Sync Data: " << state);
273 
274  if (!updates.empty()) {
275  m_onUpdate(updates);
276  }
277 
279 }
280 
281 } // namespace psync
Consumer logic to subscribe to producer's data.
Definition: consumer.hpp:56
bool addSubscription(const ndn::Name &prefix, uint64_t seqNo, bool callSyncDataCb=true)
Add prefix to subscription list.
Definition: consumer.cpp:55
bool removeSubscription(const ndn::Name &prefix)
Remove prefix from subscription list.
Definition: consumer.cpp:75
void stop()
Stop segment fetcher to stop the sync and free resources.
Definition: consumer.cpp:95
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
void sendHelloInterest()
send hello interest /<sync-prefix>/hello/
Definition: consumer.cpp:112
void sendSyncInterest()
send sync interest /<sync-prefix>/sync/<BF>/<producers-IBF>
Definition: consumer.cpp:186
bool isSubscribed(const ndn::Name &prefix) const
Definition: consumer.hpp:126
void insert(const ndn::Name &key)
void appendToName(ndn::Name &name) const
Append our bloom filter to the given name.
Definition: common.hpp:34
std::function< void(const std::vector< MissingDataInfo > &)> UpdateCallback
Definition: common.hpp:71
std::function< void(const std::map< ndn::Name, uint64_t > &)> ReceiveHelloCallback
Definition: consumer.hpp:36