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-2024, 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/asio/post.hpp>
38 #include <boost/range/adaptor/reversed.hpp>
39 
40 namespace nfd::fw {
41 
42 NFD_LOG_INIT(SelfLearningStrategy);
44 
45 constexpr time::milliseconds 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("SelfLearningStrategy does not support version " +
56  std::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
69 SelfLearningStrategy::afterReceiveInterest(const Interest& interest, const FaceEndpoint& ingress,
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->findInRecord(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_INTEREST_FROM(interest, ingress, "non-discovery no-nexthop");
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
103 SelfLearningStrategy::afterReceiveData(const Data& data, const FaceEndpoint& ingress,
104  const shared_ptr<pit::Entry>& pitEntry)
105 {
106  auto outRecord = pitEntry->findOutRecord(ingress.face);
107  if (outRecord == pitEntry->out_end()) {
108  NFD_LOG_DATA_FROM(data, 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
133 SelfLearningStrategy::afterReceiveNack(const lp::Nack& nack, const FaceEndpoint& ingress,
134  const shared_ptr<pit::Entry>& pitEntry)
135 {
136  NFD_LOG_NACK_FROM(nack, ingress, "");
137 
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_INTEREST_FROM(interest, inFace.getId(), "send discovery 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_INTEREST_FROM(interest, inFace.getId(), "send non-discovery to=" << outFace.getId());
177  auto outRecord = this->sendInterest(interest, outFace, pitEntry);
178  if (outRecord != nullptr) {
179  outRecord->insertStrategyInfo<OutRecordInfo>().first->isNonDiscoveryInterest = true;
180  }
181  }
182 }
183 
184 void
185 SelfLearningStrategy::asyncProcessData(const shared_ptr<pit::Entry>& pitEntry, const Face& inFace, const Data& data)
186 {
187  // Given that this processing is asynchronous, the PIT entry's expiry timer is extended first
188  // to ensure that the entry will not be removed before the whole processing is finished
189  // (the PIT entry's expiry timer was set to 0 before dispatching)
190  this->setExpiryTimer(pitEntry, 1_s);
191 
192  boost::asio::post(getRibIoService(),
193  [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  boost::asio::post(getMainIoService(),
198  [this, pitEntryWeak, inFaceId, data, pa = std::move(*paOpt)] {
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  boost::asio::post(getRibIoService(),
242  [pitEntryWeak = weak_ptr<pit::Entry>{pitEntry}, inFaceId = inFace.getId(), data, pa] {
245  NFD_LOG_DEBUG("Add route via PrefixAnnouncement with result=" << res);
246  });
247  });
248 }
249 
250 void
251 SelfLearningStrategy::renewRoute(const Name& name, FaceId inFaceId, time::milliseconds maxLifetime)
252 {
253  // renew route with PA or ignore PA (if route has no PA)
254  boost::asio::post(getRibIoService(),
255  [name, inFaceId, maxLifetime] {
256  rib::Service::get().getRibManager().slRenew(name, inFaceId, maxLifetime,
258  NFD_LOG_DEBUG("Renew route with result=" << res);
259  });
260  });
261 }
262 
263 } // 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:118
FaceId getId() const noexcept
Returns the face ID.
Definition: face.hpp:195
Represents an entry in the FIB.
Definition: fib-entry.hpp:91
const NextHopList & getNextHops() const noexcept
Definition: fib-entry.hpp:103
bool hasNextHops() const noexcept
Returns whether this Entry has any NextHop records.
Definition: fib-entry.hpp:112
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:46
void rejectPendingInterest(const shared_ptr< pit::Entry > &pitEntry)
Schedule the PIT entry for immediate deletion.
Definition: strategy.hpp:335
const FaceTable & getFaceTable() const noexcept
Definition: strategy.hpp:411
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:291
const fib::Entry & lookupFib(const pit::Entry &pitEntry) const
Performs a FIB lookup, considering Link object if present.
Definition: strategy.cpp:313
bool sendNack(const lp::NackHeader &header, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send a Nack packet.
Definition: strategy.hpp:351
pit::OutRecord * sendInterest(const Interest &interest, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send an Interest packet.
Definition: strategy.cpp:236
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:386
void setInstanceName(const Name &name) noexcept
Set strategy instance name.
Definition: strategy.hpp:448
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:269
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:48
std::vector< NextHop > NextHopList
A collection of nexthops in a FIB entry.
Definition: fib-entry.hpp:84
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:131
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:33
boost::asio::io_context & getRibIoService()
Definition: global.cpp:70
#define NFD_LOG_INTEREST_FROM(interest, ingress, msg)
Logs the reception of interest on ingress, followed by msg, at DEBUG level.
Definition: strategy.hpp:542
#define NFD_LOG_DATA_FROM(data, ingress, msg)
Logs the reception of data on ingress, followed by msg, at DEBUG level.
Definition: strategy.hpp:549
#define NFD_LOG_NACK_FROM(nack, ingress, msg)
Logs the reception of nack on ingress, followed by msg, at DEBUG level.
Definition: strategy.hpp:555
std::optional< uint64_t > version
The strategy version number, if present.
Definition: strategy.hpp:420
PartialName parameters
Parameter components, may be empty.
Definition: strategy.hpp:421