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 
26 #include "strategy.hpp"
27 #include "forwarder.hpp"
28 #include "common/logger.hpp"
29 
30 #include <ndn-cxx/lp/pit-token.hpp>
31 
32 #include <boost/range/adaptor/map.hpp>
33 #include <boost/range/algorithm/copy.hpp>
34 #include <unordered_set>
35 
36 namespace nfd::fw {
37 
38 NFD_LOG_INIT(Strategy);
39 
40 Strategy::Registry&
41 Strategy::getRegistry()
42 {
43  static Registry registry;
44  return registry;
45 }
46 
47 Strategy::Registry::const_iterator
48 Strategy::find(const Name& instanceName)
49 {
50  const Registry& registry = getRegistry();
51  ParsedInstanceName parsed = parseInstanceName(instanceName);
52 
53  if (parsed.version) {
54  // specified version: find exact or next higher version
55 
56  auto found = registry.lower_bound(parsed.strategyName);
57  if (found != registry.end()) {
58  if (parsed.strategyName.getPrefix(-1).isPrefixOf(found->first)) {
59  NFD_LOG_TRACE("find " << instanceName << " versioned found=" << found->first);
60  return found;
61  }
62  }
63 
64  NFD_LOG_TRACE("find " << instanceName << " versioned not-found");
65  return registry.end();
66  }
67 
68  // no version specified: find highest version
69 
70  if (!parsed.strategyName.empty()) { // Name().getSuccessor() would be invalid
71  auto found = registry.lower_bound(parsed.strategyName.getSuccessor());
72  if (found != registry.begin()) {
73  --found;
74  if (parsed.strategyName.isPrefixOf(found->first)) {
75  NFD_LOG_TRACE("find " << instanceName << " unversioned found=" << found->first);
76  return found;
77  }
78  }
79  }
80 
81  NFD_LOG_TRACE("find " << instanceName << " unversioned not-found");
82  return registry.end();
83 }
84 
85 bool
86 Strategy::canCreate(const Name& instanceName)
87 {
88  return Strategy::find(instanceName) != getRegistry().end();
89 }
90 
91 unique_ptr<Strategy>
92 Strategy::create(const Name& instanceName, Forwarder& forwarder)
93 {
94  auto found = Strategy::find(instanceName);
95  if (found == getRegistry().end()) {
96  NFD_LOG_DEBUG("create " << instanceName << " not-found");
97  return nullptr;
98  }
99 
100  unique_ptr<Strategy> instance = found->second(forwarder, instanceName);
101  NFD_LOG_DEBUG("create " << instanceName << " found=" << found->first
102  << " created=" << instance->getInstanceName());
103  BOOST_ASSERT(!instance->getInstanceName().empty());
104  return instance;
105 }
106 
107 bool
108 Strategy::areSameType(const Name& instanceNameA, const Name& instanceNameB)
109 {
110  return Strategy::find(instanceNameA) == Strategy::find(instanceNameB);
111 }
112 
113 std::set<Name>
115 {
116  std::set<Name> strategyNames;
117  boost::copy(getRegistry() | boost::adaptors::map_keys,
118  std::inserter(strategyNames, strategyNames.end()));
119  return strategyNames;
120 }
121 
123 Strategy::parseInstanceName(const Name& input)
124 {
125  for (ssize_t i = input.size() - 1; i > 0; --i) {
126  if (input[i].isVersion()) {
127  return {input.getPrefix(i + 1), input[i].toVersion(), input.getSubName(i + 1)};
128  }
129  }
130  return {input, std::nullopt, PartialName()};
131 }
132 
133 Name
134 Strategy::makeInstanceName(const Name& input, const Name& strategyName)
135 {
136  BOOST_ASSERT(strategyName.at(-1).isVersion());
137 
138  bool hasVersion = std::any_of(input.rbegin(), input.rend(),
139  [] (const auto& comp) { return comp.isVersion(); });
140  return hasVersion ? input : Name(input).append(strategyName.at(-1));
141 }
142 
144 Strategy::parseParameters(const PartialName& params)
145 {
146  StrategyParameters parsed;
147 
148  for (const auto& component : params) {
149  auto sep = std::find(component.value_begin(), component.value_end(), '~');
150  if (sep == component.value_end()) {
151  NDN_THROW(std::invalid_argument("Strategy parameters format is (<parameter>~<value>)*"));
152  }
153 
154  std::string p(component.value_begin(), sep);
155  std::advance(sep, 1);
156  std::string v(sep, component.value_end());
157  if (p.empty() || v.empty()) {
158  NDN_THROW(std::invalid_argument("Strategy parameter name and value cannot be empty"));
159  }
160  parsed[std::move(p)] = std::move(v);
161  }
162 
163  return parsed;
164 }
165 
167  : afterAddFace(forwarder.m_faceTable.afterAdd)
168  , beforeRemoveFace(forwarder.m_faceTable.beforeRemove)
169  , m_forwarder(forwarder)
170  , m_measurements(m_forwarder.getMeasurements(), m_forwarder.getStrategyChoice(), *this)
171 {
172 }
173 
174 Strategy::~Strategy() = default;
175 
176 void
177 Strategy::onInterestLoop(const Interest& interest, const FaceEndpoint& ingress)
178 {
179  NFD_LOG_DEBUG("onInterestLoop in=" << ingress << " name=" << interest.getName());
180 
181  lp::Nack nack(interest);
182  nack.setReason(lp::NackReason::DUPLICATE);
183  this->sendNack(nack, ingress.face);
184 }
185 
186 void
187 Strategy::afterContentStoreHit(const Data& data, const FaceEndpoint& ingress,
188  const shared_ptr<pit::Entry>& pitEntry)
189 {
190  NFD_LOG_DEBUG("afterContentStoreHit pitEntry=" << pitEntry->getName()
191  << " in=" << ingress << " data=" << data.getName());
192 
193  this->sendData(data, ingress.face, pitEntry);
194 }
195 
196 void
197 Strategy::beforeSatisfyInterest(const Data& data, const FaceEndpoint& ingress,
198  const shared_ptr<pit::Entry>& pitEntry)
199 {
200  NFD_LOG_DEBUG("beforeSatisfyInterest pitEntry=" << pitEntry->getName()
201  << " in=" << ingress << " data=" << data.getName());
202 }
203 
204 void
205 Strategy::afterReceiveData(const Data& data, const FaceEndpoint& ingress,
206  const shared_ptr<pit::Entry>& pitEntry)
207 {
208  NFD_LOG_DEBUG("afterReceiveData pitEntry=" << pitEntry->getName()
209  << " in=" << ingress << " data=" << data.getName());
210 
211  this->beforeSatisfyInterest(data, ingress, pitEntry);
212  this->sendDataToAll(data, pitEntry, ingress.face);
213 }
214 
215 void
216 Strategy::afterReceiveNack(const lp::Nack&, const FaceEndpoint& ingress,
217  const shared_ptr<pit::Entry>& pitEntry)
218 {
219  NFD_LOG_DEBUG("afterReceiveNack in=" << ingress << " pitEntry=" << pitEntry->getName());
220 }
221 
222 void
223 Strategy::onDroppedInterest(const Interest& interest, Face& egress)
224 {
225  NFD_LOG_DEBUG("onDroppedInterest out=" << egress.getId() << " name=" << interest.getName());
226 }
227 
228 void
229 Strategy::afterNewNextHop(const fib::NextHop& nextHop, const shared_ptr<pit::Entry>& pitEntry)
230 {
231  NFD_LOG_DEBUG("afterNewNextHop pitEntry=" << pitEntry->getName()
232  << " nexthop=" << nextHop.getFace().getId());
233 }
234 
236 Strategy::sendInterest(const Interest& interest, Face& egress, const shared_ptr<pit::Entry>& pitEntry)
237 {
238  if (interest.getTag<lp::PitToken>() != nullptr) {
239  Interest interest2 = interest; // make a copy to preserve tag on original packet
240  interest2.removeTag<lp::PitToken>();
241  return m_forwarder.onOutgoingInterest(interest2, egress, pitEntry);
242  }
243  return m_forwarder.onOutgoingInterest(interest, egress, pitEntry);
244 }
245 
246 bool
247 Strategy::sendData(const Data& data, Face& egress, const shared_ptr<pit::Entry>& pitEntry)
248 {
249  BOOST_ASSERT(pitEntry->getInterest().matchesData(data));
250 
251  auto inRecord = pitEntry->findInRecord(egress);
252  if (inRecord != pitEntry->in_end()) {
253  auto pitToken = inRecord->getInterest().getTag<lp::PitToken>();
254 
255  // delete the PIT entry's in-record based on egress,
256  // since the Data is sent to the face from which the Interest was received
257  pitEntry->deleteInRecord(inRecord);
258 
259  if (pitToken != nullptr) {
260  Data data2 = data; // make a copy so each downstream can get a different PIT token
261  data2.setTag(pitToken);
262  return m_forwarder.onOutgoingData(data2, egress);
263  }
264  }
265  return m_forwarder.onOutgoingData(data, egress);
266 }
267 
268 void
269 Strategy::sendDataToAll(const Data& data, const shared_ptr<pit::Entry>& pitEntry, const Face& inFace)
270 {
271  std::set<Face*> pendingDownstreams;
272  auto now = time::steady_clock::now();
273 
274  // remember pending downstreams
275  for (const auto& inRecord : pitEntry->getInRecords()) {
276  if (inRecord.getExpiry() > now) {
277  if (inRecord.getFace().getId() == inFace.getId() &&
278  inRecord.getFace().getLinkType() != ndn::nfd::LINK_TYPE_AD_HOC) {
279  continue;
280  }
281  pendingDownstreams.emplace(&inRecord.getFace());
282  }
283  }
284 
285  for (const auto& pendingDownstream : pendingDownstreams) {
286  this->sendData(data, *pendingDownstream, pitEntry);
287  }
288 }
289 
290 void
291 Strategy::sendNacks(const lp::NackHeader& header, const shared_ptr<pit::Entry>& pitEntry,
292  std::initializer_list<const Face*> exceptFaces)
293 {
294  // populate downstreams with all downstreams faces
295  std::unordered_set<Face*> downstreams;
296  std::transform(pitEntry->in_begin(), pitEntry->in_end(),
297  std::inserter(downstreams, downstreams.end()),
298  [] (const auto& inR) { return &inR.getFace(); });
299 
300  // remove excluded faces
301  for (auto exceptFace : exceptFaces) {
302  downstreams.erase(const_cast<Face*>(exceptFace));
303  }
304 
305  // send Nacks
306  for (auto downstream : downstreams) {
307  this->sendNack(header, *downstream, pitEntry);
308  }
309  // warning: don't loop on pitEntry->getInRecords(), because in-record is deleted when sending Nack
310 }
311 
312 const fib::Entry&
313 Strategy::lookupFib(const pit::Entry& pitEntry) const
314 {
315  const Fib& fib = m_forwarder.getFib();
316 
317  const Interest& interest = pitEntry.getInterest();
318  // has forwarding hint?
319  if (interest.getForwardingHint().empty()) {
320  // FIB lookup with Interest name
321  const fib::Entry& fibEntry = fib.findLongestPrefixMatch(pitEntry);
322  NFD_LOG_TRACE("lookupFib noForwardingHint found=" << fibEntry.getPrefix());
323  return fibEntry;
324  }
325 
326  const auto& fh = interest.getForwardingHint();
327  // Forwarding hint should have been stripped by incoming Interest pipeline when reaching producer region
328  BOOST_ASSERT(!m_forwarder.getNetworkRegionTable().isInProducerRegion(fh));
329 
330  const fib::Entry* fibEntry = nullptr;
331  for (const auto& delegation : fh) {
332  fibEntry = &fib.findLongestPrefixMatch(delegation);
333  if (fibEntry->hasNextHops()) {
334  if (fibEntry->getPrefix().empty()) {
335  // in consumer region, return the default route
336  NFD_LOG_TRACE("lookupFib inConsumerRegion found=" << fibEntry->getPrefix());
337  }
338  else {
339  // in default-free zone, use the first delegation that finds a FIB entry
340  NFD_LOG_TRACE("lookupFib delegation=" << delegation << " found=" << fibEntry->getPrefix());
341  }
342  return *fibEntry;
343  }
344  BOOST_ASSERT(fibEntry->getPrefix().empty()); // only ndn:/ FIB entry can have zero nexthop
345  }
346  BOOST_ASSERT(fibEntry != nullptr && fibEntry->getPrefix().empty());
347  return *fibEntry; // only occurs if no delegation finds a FIB nexthop
348 }
349 
350 } // namespace nfd::fw
Represents a face-endpoint pair in the forwarder.
Main class of NFD's forwarding engine.
Definition: forwarder.hpp:54
Fib & getFib() noexcept
Definition: forwarder.hpp:90
NetworkRegionTable & getNetworkRegionTable() noexcept
Definition: forwarder.hpp:126
bool isInProducerRegion(span< const Name > forwardingHint) const
Determines whether an Interest has reached a producer region.
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
bool hasNextHops() const noexcept
Returns whether this Entry has any NextHop records.
Definition: fib-entry.hpp:112
const Name & getPrefix() const noexcept
Definition: fib-entry.hpp:97
Represents the Forwarding Information Base (FIB).
Definition: fib.hpp:51
const Entry & findLongestPrefixMatch(const Name &prefix) const
Performs a longest prefix match.
Definition: fib.cpp:57
Represents a nexthop record in a FIB entry.
Definition: fib-entry.hpp:50
Face & getFace() const noexcept
Definition: fib-entry.hpp:59
virtual void onDroppedInterest(const Interest &interest, Face &egress)
Trigger after an Interest is dropped (e.g., for exceeding allowed retransmissions).
Definition: strategy.cpp:223
virtual void afterContentStoreHit(const Data &data, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry)
Trigger after a matching Data is found in the Content Store.
Definition: strategy.cpp:187
virtual void afterReceiveNack(const lp::Nack &nack, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry)
Trigger after a Nack is received.
Definition: strategy.cpp:216
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
Strategy(Forwarder &forwarder)
Construct a strategy instance.
Definition: strategy.cpp:166
static bool canCreate(const Name &instanceName)
Returns whether a strategy instance can be created from instanceName.
Definition: strategy.cpp:86
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
virtual void afterNewNextHop(const fib::NextHop &nextHop, const shared_ptr< pit::Entry > &pitEntry)
Trigger after a new nexthop is added.
Definition: strategy.cpp:229
pit::OutRecord * sendInterest(const Interest &interest, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send an Interest packet.
Definition: strategy.cpp:236
bool sendData(const Data &data, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send a Data packet.
Definition: strategy.cpp:247
static ParsedInstanceName parseInstanceName(const Name &input)
Parse a strategy instance name.
Definition: strategy.cpp:123
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
virtual void onInterestLoop(const Interest &interest, const FaceEndpoint &ingress)
Trigger after an Interest loop is detected.
Definition: strategy.cpp:177
virtual ~Strategy()
virtual void afterReceiveData(const Data &data, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry)
Trigger after Data is received.
Definition: strategy.cpp:205
static std::set< Name > listRegistered()
Returns all registered versioned strategy names.
Definition: strategy.cpp:114
static StrategyParameters parseParameters(const PartialName &params)
Parse strategy parameters encoded in a strategy instance name.
Definition: strategy.cpp:144
virtual void beforeSatisfyInterest(const Data &data, const FaceEndpoint &ingress, const shared_ptr< pit::Entry > &pitEntry)
Trigger before a PIT entry is satisfied.
Definition: strategy.cpp:197
static Name makeInstanceName(const Name &input, const Name &strategyName)
Construct a strategy instance name.
Definition: strategy.cpp:134
static unique_ptr< Strategy > create(const Name &instanceName, Forwarder &forwarder)
Returns a strategy instance created from instanceName.
Definition: strategy.cpp:92
static bool areSameType(const Name &instanceNameA, const Name &instanceNameB)
Returns whether two names will instantiate the same strategy type.
Definition: strategy.cpp:108
Represents an entry in the Interest table (PIT).
Definition: pit-entry.hpp:197
const Interest & getInterest() const
Definition: pit-entry.hpp:208
Contains information about an Interest toward an outgoing face.
Definition: pit-entry.hpp:129
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
#define NFD_LOG_DEBUG
Definition: logger.hpp:38
#define NFD_LOG_TRACE
Definition: logger.hpp:37