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-2022, 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 
33 #include <ndn-cxx/lp/empty-value.hpp>
34 #include <ndn-cxx/lp/prefix-announcement-header.hpp>
35 #include <ndn-cxx/lp/tags.hpp>
36 
37 #include <boost/range/adaptor/reversed.hpp>
38 
39 namespace nfd::fw {
40 
41 NFD_LOG_INIT(SelfLearningStrategy);
43 
44 constexpr time::milliseconds ROUTE_RENEW_LIFETIME = 10_min;
45 
47  : Strategy(forwarder)
48 {
50  if (!parsed.parameters.empty()) {
51  NDN_THROW(std::invalid_argument("SelfLearningStrategy does not accept parameters"));
52  }
53  if (parsed.version && *parsed.version != getStrategyName()[-1].toVersion()) {
54  NDN_THROW(std::invalid_argument(
55  "SelfLearningStrategy does not support version " + to_string(*parsed.version)));
56  }
58 }
59 
60 const Name&
62 {
63  static const auto strategyName = Name("/localhost/nfd/strategy/self-learning").appendVersion(1);
64  return strategyName;
65 }
66 
67 void
68 SelfLearningStrategy::afterReceiveInterest(const Interest& interest, const FaceEndpoint& ingress,
69  const shared_ptr<pit::Entry>& pitEntry)
70 {
71  const fib::Entry& fibEntry = this->lookupFib(*pitEntry);
72  const fib::NextHopList& nexthops = fibEntry.getNextHops();
73 
74  bool isNonDiscovery = interest.getTag<lp::NonDiscoveryTag>() != nullptr;
75  auto inRecordInfo = pitEntry->getInRecord(ingress.face)->insertStrategyInfo<InRecordInfo>().first;
76  if (isNonDiscovery) { // "non-discovery" Interest
77  inRecordInfo->isNonDiscoveryInterest = true;
78  if (nexthops.empty()) { // return NACK if no matching FIB entry exists
79  NFD_LOG_DEBUG("NACK non-discovery Interest=" << interest << " from=" << ingress << " noNextHop");
80  lp::NackHeader nackHeader;
81  nackHeader.setReason(lp::NackReason::NO_ROUTE);
82  this->sendNack(nackHeader, ingress.face, pitEntry);
83  this->rejectPendingInterest(pitEntry);
84  }
85  else { // multicast it if matching FIB entry exists
86  multicastInterest(interest, ingress.face, pitEntry, nexthops);
87  }
88  }
89  else { // "discovery" Interest
90  inRecordInfo->isNonDiscoveryInterest = false;
91  if (nexthops.empty()) { // broadcast it if no matching FIB entry exists
92  broadcastInterest(interest, ingress.face, pitEntry);
93  }
94  else { // multicast it with "non-discovery" mark if matching FIB entry exists
95  interest.setTag(make_shared<lp::NonDiscoveryTag>(lp::EmptyValue{}));
96  multicastInterest(interest, ingress.face, pitEntry, nexthops);
97  }
98  }
99 }
100 
101 void
102 SelfLearningStrategy::afterReceiveData(const Data& data, const FaceEndpoint& ingress,
103  const shared_ptr<pit::Entry>& pitEntry)
104 {
105  auto outRecord = pitEntry->getOutRecord(ingress.face);
106  if (outRecord == pitEntry->out_end()) {
107  NFD_LOG_DEBUG("Data " << data.getName() << " from=" << ingress << " no out-record");
108  return;
109  }
110 
111  OutRecordInfo* outRecordInfo = outRecord->getStrategyInfo<OutRecordInfo>();
112  if (outRecordInfo && outRecordInfo->isNonDiscoveryInterest) { // outgoing Interest was non-discovery
113  if (!needPrefixAnn(pitEntry)) { // no need to attach a PA (common cases)
114  sendDataToAll(data, pitEntry, ingress.face);
115  }
116  else { // needs a PA (to respond discovery Interest)
117  asyncProcessData(pitEntry, ingress.face, data);
118  }
119  }
120  else { // outgoing Interest was discovery
121  auto paTag = data.getTag<lp::PrefixAnnouncementTag>();
122  if (paTag != nullptr) {
123  addRoute(pitEntry, ingress.face, data, *paTag->get().getPrefixAnn());
124  }
125  else { // Data contains no PrefixAnnouncement, upstreams do not support self-learning
126  }
127  sendDataToAll(data, pitEntry, ingress.face);
128  }
129 }
130 
131 void
132 SelfLearningStrategy::afterReceiveNack(const lp::Nack& nack, const FaceEndpoint& ingress,
133  const shared_ptr<pit::Entry>& pitEntry)
134 {
135  NFD_LOG_DEBUG("Nack for " << nack.getInterest() << " from=" << ingress
136  << " reason=" << nack.getReason());
137  if (nack.getReason() == lp::NackReason::NO_ROUTE) { // remove FIB entries
138  BOOST_ASSERT(this->lookupFib(*pitEntry).hasNextHops());
139  NFD_LOG_DEBUG("Send NACK to all downstreams");
140  this->sendNacks(nack.getHeader(), pitEntry);
141  renewRoute(nack.getInterest().getName(), ingress.face.getId(), 0_ms);
142  }
143 }
144 
145 void
146 SelfLearningStrategy::broadcastInterest(const Interest& interest, const Face& inFace,
147  const shared_ptr<pit::Entry>& pitEntry)
148 {
149  for (auto& outFace : this->getFaceTable() | boost::adaptors::reversed) {
150  if ((outFace.getId() == inFace.getId() && outFace.getLinkType() != ndn::nfd::LINK_TYPE_AD_HOC) ||
151  wouldViolateScope(inFace, interest, outFace) ||
152  outFace.getScope() == ndn::nfd::FACE_SCOPE_LOCAL) {
153  continue;
154  }
155 
156  NFD_LOG_DEBUG("send discovery Interest=" << interest << " from=" << inFace.getId() <<
157  " to=" << outFace.getId());
158  auto outRecord = this->sendInterest(interest, outFace, pitEntry);
159  if (outRecord != nullptr) {
160  outRecord->insertStrategyInfo<OutRecordInfo>().first->isNonDiscoveryInterest = false;
161  }
162  }
163 }
164 
165 void
166 SelfLearningStrategy::multicastInterest(const Interest& interest, const Face& inFace,
167  const shared_ptr<pit::Entry>& pitEntry,
168  const fib::NextHopList& nexthops)
169 {
170  for (const auto& nexthop : nexthops) {
171  if (!isNextHopEligible(inFace, interest, nexthop, pitEntry)) {
172  continue;
173  }
174 
175  Face& outFace = nexthop.getFace();
176  NFD_LOG_DEBUG("send non-discovery Interest=" << interest << " from=" << inFace.getId() <<
177  " to=" << outFace.getId());
178  auto outRecord = this->sendInterest(interest, outFace, pitEntry);
179  if (outRecord != nullptr) {
180  outRecord->insertStrategyInfo<OutRecordInfo>().first->isNonDiscoveryInterest = true;
181  }
182  }
183 }
184 
185 void
186 SelfLearningStrategy::asyncProcessData(const shared_ptr<pit::Entry>& pitEntry, const Face& inFace, const Data& data)
187 {
188  // Given that this processing is asynchronous, the PIT entry's expiry timer is extended first
189  // to ensure that the entry will not be removed before the whole processing is finished
190  // (the PIT entry's expiry timer was set to 0 before dispatching)
191  this->setExpiryTimer(pitEntry, 1_s);
192 
193  runOnRibIoService([this, pitEntryWeak = weak_ptr<pit::Entry>{pitEntry}, inFaceId = inFace.getId(), data] {
194  rib::Service::get().getRibManager().slFindAnn(data.getName(),
195  [this, pitEntryWeak, inFaceId, data] (std::optional<ndn::PrefixAnnouncement> paOpt) {
196  if (paOpt) {
197  runOnMainIoService([this, pitEntryWeak, inFaceId, data, pa = std::move(*paOpt)] {
198  auto pitEntry = pitEntryWeak.lock();
199  auto inFace = this->getFace(inFaceId);
200  if (pitEntry && inFace) {
201  NFD_LOG_DEBUG("found PrefixAnnouncement=" << pa.getAnnouncedName());
202  data.setTag(make_shared<lp::PrefixAnnouncementTag>(lp::PrefixAnnouncementHeader(pa)));
203  this->sendDataToAll(data, pitEntry, *inFace);
204  this->setExpiryTimer(pitEntry, 0_ms);
205  }
206  else {
207  NFD_LOG_DEBUG("PIT entry or Face no longer exists");
208  }
209  });
210  }
211  });
212  });
213 }
214 
215 bool
216 SelfLearningStrategy::needPrefixAnn(const shared_ptr<pit::Entry>& pitEntry)
217 {
218  bool hasDiscoveryInterest = false;
219  bool directToConsumer = true;
220 
221  auto now = time::steady_clock::now();
222  for (const auto& inRecord : pitEntry->getInRecords()) {
223  if (inRecord.getExpiry() > now) {
224  InRecordInfo* inRecordInfo = inRecord.getStrategyInfo<InRecordInfo>();
225  if (inRecordInfo && !inRecordInfo->isNonDiscoveryInterest) {
226  hasDiscoveryInterest = true;
227  }
228  if (inRecord.getFace().getScope() != ndn::nfd::FACE_SCOPE_LOCAL) {
229  directToConsumer = false;
230  }
231  }
232  }
233  return hasDiscoveryInterest && !directToConsumer;
234 }
235 
236 void
237 SelfLearningStrategy::addRoute(const shared_ptr<pit::Entry>& pitEntry, const Face& inFace,
238  const Data& data, const ndn::PrefixAnnouncement& pa)
239 {
240  runOnRibIoService([pitEntryWeak = weak_ptr<pit::Entry>{pitEntry}, inFaceId = inFace.getId(), data, pa] {
243  NFD_LOG_DEBUG("Add route via PrefixAnnouncement with result=" << res);
244  });
245  });
246 }
247 
248 void
249 SelfLearningStrategy::renewRoute(const Name& name, FaceId inFaceId, time::milliseconds maxLifetime)
250 {
251  // renew route with PA or ignore PA (if route has no PA)
252  runOnRibIoService([name, inFaceId, maxLifetime] {
253  rib::Service::get().getRibManager().slRenew(name, inFaceId, maxLifetime,
255  NFD_LOG_DEBUG("Renew route with result=" << res);
256  });
257  });
258 }
259 
260 } // namespace nfd::fw
This file contains common algorithms used by forwarding strategies.
Represents a face-endpoint pair in the forwarder.
Main class of NFD's forwarding engine.
Definition: forwarder.hpp:54
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.
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 slFindAnn(const Name &name, const SlFindAnnCallback &cb) const
Retrieve an outgoing prefix announcement for self-learning strategy.
Generalization of a network interface.
Definition: face.hpp:56
FaceId getId() const noexcept
Returns the face ID.
Definition: face.hpp:121
Represents an entry in the FIB.
Definition: fib-entry.hpp:54
const NextHopList & getNextHops() const
Definition: fib-entry.hpp:66
bool hasNextHops() const
Definition: fib-entry.hpp:74
Self-learning forwarding strategy.
void afterReceiveNack(const lp::Nack &nack, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry) override
Trigger after a Nack is received.
void afterReceiveData(const Data &data, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry) override
Trigger after Data is received.
void afterReceiveInterest(const Interest &interest, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry) override
Trigger after an Interest is received.
SelfLearningStrategy(Forwarder &forwarder, const Name &name=getStrategyName())
Base class of all forwarding strategies.
Definition: strategy.hpp:42
void rejectPendingInterest(const shared_ptr< pit::Entry > &pitEntry)
Schedule the PIT entry for immediate deletion.
Definition: strategy.hpp:317
const FaceTable & getFaceTable() const noexcept
Definition: strategy.hpp:378
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:282
const fib::Entry & lookupFib(const pit::Entry &pitEntry) const
Performs a FIB lookup, considering Link object if present.
Definition: strategy.cpp:304
bool sendNack(const lp::NackHeader &header, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send a Nack packet.
Definition: strategy.hpp:333
pit::OutRecord * sendInterest(const Interest &interest, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send an Interest packet.
Definition: strategy.cpp:226
static ParsedInstanceName parseInstanceName(const Name &input)
Parse a strategy instance name.
Definition: strategy.cpp:123
void setExpiryTimer(const shared_ptr< pit::Entry > &pitEntry, time::milliseconds duration)
Schedule the PIT entry to be erased after duration.
Definition: strategy.hpp:353
void setInstanceName(const Name &name) noexcept
Set strategy instance name.
Definition: strategy.hpp:415
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:260
static Name makeInstanceName(const Name &input, const Name &strategyName)
Construct a strategy instance name.
Definition: strategy.cpp:134
static Service & get()
Get a reference to the only instance of this class.
Definition: service.cpp:139
RibManager & getRibManager() noexcept
Definition: service.hpp:86
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
#define NFD_LOG_DEBUG
Definition: logger.hpp:38
uint64_t FaceId
Identifies a face.
Definition: face-common.hpp:47
std::vector< NextHop > NextHopList
Definition: fib-entry.hpp:47
constexpr time::milliseconds ROUTE_RENEW_LIFETIME
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)
Determines whether a NextHop is eligible, i.e., not the same inFace.
Definition: algorithm.cpp:130
NFD_REGISTER_STRATEGY(SelfLearningStrategy)
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:32
void runOnRibIoService(const std::function< void()> &f)
Run a function on the RIB io_service instance.
Definition: global.cpp:95
std::optional< uint64_t > version
The strategy version number, if present.
Definition: strategy.hpp:387
PartialName parameters
Parameter components, may be empty.
Definition: strategy.hpp:388