NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
self-learning-strategy.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2021, Regents of the University of California,
4  * Arizona Board of Regents,
5  * Colorado State University,
6  * University Pierre & Marie Curie, Sorbonne University,
7  * Washington University in St. Louis,
8  * Beijing Institute of Technology,
9  * The University of Memphis.
10  *
11  * This file is part of NFD (Named Data Networking Forwarding Daemon).
12  * See AUTHORS.md for complete list of NFD authors and contributors.
13  *
14  * NFD is free software: you can redistribute it and/or modify it under the terms
15  * of the GNU General Public License as published by the Free Software Foundation,
16  * either version 3 of the License, or (at your option) any later version.
17  *
18  * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
19  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
20  * PURPOSE. See the GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along with
23  * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
24  */
25 
27 #include "algorithm.hpp"
28 
29 #include "common/global.hpp"
30 #include "common/logger.hpp"
31 #include "rib/service.hpp"
32 
35 #include <ndn-cxx/lp/tags.hpp>
36 
37 #include <boost/range/adaptor/reversed.hpp>
38 
39 namespace nfd {
40 namespace fw {
41 
44 
45 const time::milliseconds SelfLearningStrategy::ROUTE_RENEW_LIFETIME(10_min);
46 
48  : Strategy(forwarder)
49 {
51  if (!parsed.parameters.empty()) {
52  NDN_THROW(std::invalid_argument("SelfLearningStrategy does not accept parameters"));
53  }
54  if (parsed.version && *parsed.version != getStrategyName()[-1].toVersion()) {
55  NDN_THROW(std::invalid_argument(
56  "SelfLearningStrategy does not support version " + to_string(*parsed.version)));
57  }
59 }
60 
61 const Name&
63 {
64  static const auto strategyName = Name("/localhost/nfd/strategy/self-learning").appendVersion(1);
65  return strategyName;
66 }
67 
68 void
70  const shared_ptr<pit::Entry>& pitEntry)
71 {
72  const fib::Entry& fibEntry = this->lookupFib(*pitEntry);
73  const fib::NextHopList& nexthops = fibEntry.getNextHops();
74 
75  bool isNonDiscovery = interest.getTag<lp::NonDiscoveryTag>() != nullptr;
76  auto inRecordInfo = pitEntry->getInRecord(ingress.face)->insertStrategyInfo<InRecordInfo>().first;
77  if (isNonDiscovery) { // "non-discovery" Interest
78  inRecordInfo->isNonDiscoveryInterest = true;
79  if (nexthops.empty()) { // return NACK if no matching FIB entry exists
80  NFD_LOG_DEBUG("NACK non-discovery Interest=" << interest << " from=" << ingress << " noNextHop");
81  lp::NackHeader nackHeader;
82  nackHeader.setReason(lp::NackReason::NO_ROUTE);
83  this->sendNack(nackHeader, ingress.face, pitEntry);
84  this->rejectPendingInterest(pitEntry);
85  }
86  else { // multicast it if matching FIB entry exists
87  multicastInterest(interest, ingress.face, pitEntry, nexthops);
88  }
89  }
90  else { // "discovery" Interest
91  inRecordInfo->isNonDiscoveryInterest = false;
92  if (nexthops.empty()) { // broadcast it if no matching FIB entry exists
93  broadcastInterest(interest, ingress.face, pitEntry);
94  }
95  else { // multicast it with "non-discovery" mark if matching FIB entry exists
96  interest.setTag(make_shared<lp::NonDiscoveryTag>(lp::EmptyValue{}));
97  multicastInterest(interest, ingress.face, pitEntry, nexthops);
98  }
99  }
100 }
101 
102 void
104  const shared_ptr<pit::Entry>& pitEntry)
105 {
106  auto outRecord = pitEntry->getOutRecord(ingress.face);
107  if (outRecord == pitEntry->out_end()) {
108  NFD_LOG_DEBUG("Data " << data.getName() << " from=" << ingress << " no out-record");
109  return;
110  }
111 
112  OutRecordInfo* outRecordInfo = outRecord->getStrategyInfo<OutRecordInfo>();
113  if (outRecordInfo && outRecordInfo->isNonDiscoveryInterest) { // outgoing Interest was non-discovery
114  if (!needPrefixAnn(pitEntry)) { // no need to attach a PA (common cases)
115  sendDataToAll(data, pitEntry, ingress.face);
116  }
117  else { // needs a PA (to respond discovery Interest)
118  asyncProcessData(pitEntry, ingress.face, data);
119  }
120  }
121  else { // outgoing Interest was discovery
122  auto paTag = data.getTag<lp::PrefixAnnouncementTag>();
123  if (paTag != nullptr) {
124  addRoute(pitEntry, ingress.face, data, *paTag->get().getPrefixAnn());
125  }
126  else { // Data contains no PrefixAnnouncement, upstreams do not support self-learning
127  }
128  sendDataToAll(data, pitEntry, ingress.face);
129  }
130 }
131 
132 void
134  const shared_ptr<pit::Entry>& pitEntry)
135 {
136  NFD_LOG_DEBUG("Nack for " << nack.getInterest() << " from=" << ingress
137  << " reason=" << nack.getReason());
138  if (nack.getReason() == lp::NackReason::NO_ROUTE) { // remove FIB entries
139  BOOST_ASSERT(this->lookupFib(*pitEntry).hasNextHops());
140  NFD_LOG_DEBUG("Send NACK to all downstreams");
141  this->sendNacks(nack.getHeader(), pitEntry);
142  renewRoute(nack.getInterest().getName(), ingress.face.getId(), 0_ms);
143  }
144 }
145 
146 void
147 SelfLearningStrategy::broadcastInterest(const Interest& interest, const Face& inFace,
148  const shared_ptr<pit::Entry>& pitEntry)
149 {
150  for (auto& outFace : this->getFaceTable() | boost::adaptors::reversed) {
151  if ((outFace.getId() == inFace.getId() && outFace.getLinkType() != ndn::nfd::LINK_TYPE_AD_HOC) ||
152  wouldViolateScope(inFace, interest, outFace) ||
153  outFace.getScope() == ndn::nfd::FACE_SCOPE_LOCAL) {
154  continue;
155  }
156 
157  NFD_LOG_DEBUG("send discovery Interest=" << interest << " from=" << inFace.getId() <<
158  " to=" << outFace.getId());
159  auto outRecord = this->sendInterest(interest, outFace, pitEntry);
160  if (outRecord != nullptr) {
161  outRecord->insertStrategyInfo<OutRecordInfo>().first->isNonDiscoveryInterest = false;
162  }
163  }
164 }
165 
166 void
167 SelfLearningStrategy::multicastInterest(const Interest& interest, const Face& inFace,
168  const shared_ptr<pit::Entry>& pitEntry,
169  const fib::NextHopList& nexthops)
170 {
171  for (const auto& nexthop : nexthops) {
172  if (!isNextHopEligible(inFace, interest, nexthop, pitEntry)) {
173  continue;
174  }
175 
176  Face& outFace = nexthop.getFace();
177  NFD_LOG_DEBUG("send non-discovery Interest=" << interest << " from=" << inFace.getId() <<
178  " to=" << outFace.getId());
179  auto outRecord = this->sendInterest(interest, outFace, pitEntry);
180  if (outRecord != nullptr) {
181  outRecord->insertStrategyInfo<OutRecordInfo>().first->isNonDiscoveryInterest = true;
182  }
183  }
184 }
185 
186 void
187 SelfLearningStrategy::asyncProcessData(const shared_ptr<pit::Entry>& pitEntry, const Face& inFace, const Data& data)
188 {
189  // Given that this processing is asynchronous, the PIT entry's expiry timer is extended first
190  // to ensure that the entry will not be removed before the whole processing is finished
191  // (the PIT entry's expiry timer was set to 0 before dispatching)
192  this->setExpiryTimer(pitEntry, 1_s);
193 
194  runOnRibIoService([pitEntryWeak = weak_ptr<pit::Entry>{pitEntry}, inFaceId = inFace.getId(), data, this] {
196  [pitEntryWeak, inFaceId, data, this] (optional<ndn::PrefixAnnouncement> paOpt) {
197  if (paOpt) {
198  runOnMainIoService([pitEntryWeak, inFaceId, data, pa = std::move(*paOpt), this] {
199  auto pitEntry = pitEntryWeak.lock();
200  auto inFace = this->getFace(inFaceId);
201  if (pitEntry && inFace) {
202  NFD_LOG_DEBUG("found PrefixAnnouncement=" << pa.getAnnouncedName());
203  data.setTag(make_shared<lp::PrefixAnnouncementTag>(lp::PrefixAnnouncementHeader(pa)));
204  this->sendDataToAll(data, pitEntry, *inFace);
205  this->setExpiryTimer(pitEntry, 0_ms);
206  }
207  else {
208  NFD_LOG_DEBUG("PIT entry or Face no longer exists");
209  }
210  });
211  }
212  });
213  });
214 }
215 
216 bool
217 SelfLearningStrategy::needPrefixAnn(const shared_ptr<pit::Entry>& pitEntry)
218 {
219  bool hasDiscoveryInterest = false;
220  bool directToConsumer = true;
221 
222  auto now = time::steady_clock::now();
223  for (const auto& inRecord : pitEntry->getInRecords()) {
224  if (inRecord.getExpiry() > now) {
225  InRecordInfo* inRecordInfo = inRecord.getStrategyInfo<InRecordInfo>();
226  if (inRecordInfo && !inRecordInfo->isNonDiscoveryInterest) {
227  hasDiscoveryInterest = true;
228  }
229  if (inRecord.getFace().getScope() != ndn::nfd::FACE_SCOPE_LOCAL) {
230  directToConsumer = false;
231  }
232  }
233  }
234  return hasDiscoveryInterest && !directToConsumer;
235 }
236 
237 void
238 SelfLearningStrategy::addRoute(const shared_ptr<pit::Entry>& pitEntry, const Face& inFace,
239  const Data& data, const ndn::PrefixAnnouncement& pa)
240 {
241  runOnRibIoService([pitEntryWeak = weak_ptr<pit::Entry>{pitEntry}, inFaceId = inFace.getId(), data, pa] {
242  rib::Service::get().getRibManager().slAnnounce(pa, inFaceId, ROUTE_RENEW_LIFETIME,
244  NFD_LOG_DEBUG("Add route via PrefixAnnouncement with result=" << res);
245  });
246  });
247 }
248 
249 void
250 SelfLearningStrategy::renewRoute(const Name& name, FaceId inFaceId, time::milliseconds maxLifetime)
251 {
252  // renew route with PA or ignore PA (if route has no PA)
253  runOnRibIoService([name, inFaceId, maxLifetime] {
254  rib::Service::get().getRibManager().slRenew(name, inFaceId, maxLifetime,
256  NFD_LOG_DEBUG("Renew route with result=" << res);
257  });
258  });
259 }
260 
261 } // namespace fw
262 } // namespace nfd
void setTag(shared_ptr< T > tag) const
set a tag item
Definition: tag-host.hpp:79
void slRenew(const Name &name, uint64_t faceId, time::milliseconds maxLifetime, const SlAnnounceCallback &cb)
Renew a route created by prefix announcement from self-learning strategy.
static ParsedInstanceName parseInstanceName(const Name &input)
Parse a strategy instance name.
Definition: strategy.cpp:123
shared_ptr< T > getTag() const
get a tag item
Definition: tag-host.hpp:66
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
SelfLearningStrategy(Forwarder &forwarder, const Name &name=getStrategyName())
std::string to_string(const T &val)
Definition: backports.hpp:86
NackHeader & setReason(NackReason reason)
set reason code
void sendNacks(const lp::NackHeader &header, const shared_ptr< pit::Entry > &pitEntry, std::initializer_list< const Face *> exceptFaces={})
Send Nack to every face that has an in-record, except those in exceptFaces.
Definition: strategy.cpp:309
Represents a face-endpoint pair in the forwarder.
represents a FIB entry
Definition: fib-entry.hpp:53
PartialName parameters
parameter components
Definition: strategy.hpp:390
static time_point now() noexcept
Definition: time.cpp:80
void slAnnounce(const ndn::PrefixAnnouncement &pa, uint64_t faceId, time::milliseconds maxLifetime, const SlAnnounceCallback &cb)
Insert a route by prefix announcement from self-learning strategy.
void runOnRibIoService(const std::function< void()> &f)
Run a function on the RIB io_service instance.
Definition: global.cpp:86
Face * getFace(FaceId id) const
Definition: strategy.hpp:374
Main class of NFD&#39;s forwarding engine.
Definition: forwarder.hpp:53
void setInstanceName(const Name &name)
Set strategy instance name.
Definition: strategy.hpp:417
Represents an Interest packet.
Definition: interest.hpp:48
const NackHeader & getHeader() const
Definition: nack.hpp:63
void runOnMainIoService(const std::function< void()> &f)
Run a function on the main io_service instance.
Definition: global.cpp:80
Represents a collection of nexthops.
Definition: fib-entry.hpp:39
NFD_VIRTUAL_WITH_TESTS void rejectPendingInterest(const shared_ptr< pit::Entry > &pitEntry)
Schedule the PIT entry for immediate deletion.
Definition: strategy.hpp:319
A prefix announcement object that represents an application&#39;s intent of registering a prefix toward i...
represents a Network Nack
Definition: nack.hpp:38
#define NDN_THROW(e)
Definition: exception.hpp:61
NackReason getReason() const
Definition: nack.hpp:90
provides a tag type for simple types
Definition: tag.hpp:58
ndn Face
Definition: face-impl.hpp:42
NFD_VIRTUAL_WITH_TESTS void sendDataToAll(const Data &data, const shared_ptr< pit::Entry > &pitEntry, const Face &inFace)
Send a Data packet to all matched and qualified faces.
Definition: strategy.cpp:279
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:39
void afterReceiveData(const Data &data, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry) override
trigger after Data is received
#define NFD_LOG_DEBUG
Definition: logger.hpp:38
represents a PrefixAnnouncement header field in NDNLP
NFD_REGISTER_STRATEGY(AccessStrategy)
const Name & getName() const noexcept
Get name.
Definition: data.hpp:127
Represents an absolute name.
Definition: name.hpp:41
RibManager & getRibManager()
Definition: service.hpp:71
NFD_VIRTUAL_WITH_TESTS bool sendNack(const lp::NackHeader &header, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send a Nack packet.
Definition: strategy.hpp:335
Represents a forwarding strategy.
Definition: strategy.hpp:38
represents a zero-length TLV-VALUE
Definition: empty-value.hpp:33
static Service & get()
Get a reference to the only instance of this class.
Definition: service.cpp:92
optional< uint64_t > version
whether strategyName contains a version component
Definition: strategy.hpp:389
This file contains common algorithms used by forwarding strategies.
const fib::Entry & lookupFib(const pit::Entry &pitEntry) const
Performs a FIB lookup, considering Link object if present.
Definition: strategy.cpp:331
const FaceTable & getFaceTable() const
Definition: strategy.hpp:380
const Name & getName() const noexcept
Definition: interest.hpp:172
bool isNextHopEligible(const Face &inFace, const Interest &interest, const fib::NextHop &nexthop, const shared_ptr< pit::Entry > &pitEntry, bool wantUnused, time::steady_clock::time_point now)
Definition: algorithm.cpp:131
static Name makeInstanceName(const Name &input, const Name &strategyName)
Construct a strategy instance name.
Definition: strategy.cpp:134
void setExpiryTimer(const shared_ptr< pit::Entry > &pitEntry, time::milliseconds duration)
Schedule the PIT entry to be erased after duration.
Definition: strategy.hpp:355
const NextHopList & getNextHops() const
Definition: fib-entry.hpp:66
void slFindAnn(const Name &name, const SlFindAnnCallback &cb) const
Retrieve an outgoing prefix announcement for self-learning strategy.
NFD_VIRTUAL_WITH_TESTS pit::OutRecord * sendInterest(const Interest &interest, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send an Interest packet.
Definition: strategy.cpp:237
Represents a Data packet.
Definition: data.hpp:37
void afterReceiveInterest(const Interest &interest, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry) override
Trigger after an Interest is received.
represents a Network NACK header
Definition: nack-header.hpp:57
bool wouldViolateScope(const Face &inFace, const Interest &interest, const Face &outFace)
determine whether forwarding the Interest in pitEntry to outFace would violate scope ...
Definition: algorithm.cpp:33
uint64_t FaceId
Identifies a face.
Definition: face-common.hpp:44
void afterReceiveNack(const lp::Nack &nack, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry) override
Trigger after a Nack is received.
bool hasNextHops() const
Definition: fib-entry.hpp:74
const Interest & getInterest() const
Definition: nack.hpp:51
Self-learning forwarding strategy.
boost::chrono::milliseconds milliseconds
Definition: time.hpp:48