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 
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::afterContentStoreHit(const Data& data, const FaceEndpoint& ingress,
178  const shared_ptr<pit::Entry>& pitEntry)
179 {
180  NFD_LOG_DEBUG("afterContentStoreHit pitEntry=" << pitEntry->getName()
181  << " in=" << ingress << " data=" << data.getName());
182 
183  this->sendData(data, ingress.face, pitEntry);
184 }
185 
186 void
187 Strategy::beforeSatisfyInterest(const Data& data, const FaceEndpoint& ingress,
188  const shared_ptr<pit::Entry>& pitEntry)
189 {
190  NFD_LOG_DEBUG("beforeSatisfyInterest pitEntry=" << pitEntry->getName()
191  << " in=" << ingress << " data=" << data.getName());
192 }
193 
194 void
195 Strategy::afterReceiveData(const Data& data, const FaceEndpoint& ingress,
196  const shared_ptr<pit::Entry>& pitEntry)
197 {
198  NFD_LOG_DEBUG("afterReceiveData pitEntry=" << pitEntry->getName()
199  << " in=" << ingress << " data=" << data.getName());
200 
201  this->beforeSatisfyInterest(data, ingress, pitEntry);
202  this->sendDataToAll(data, pitEntry, ingress.face);
203 }
204 
205 void
206 Strategy::afterReceiveNack(const lp::Nack&, const FaceEndpoint& ingress,
207  const shared_ptr<pit::Entry>& pitEntry)
208 {
209  NFD_LOG_DEBUG("afterReceiveNack in=" << ingress << " pitEntry=" << pitEntry->getName());
210 }
211 
212 void
213 Strategy::onDroppedInterest(const Interest& interest, Face& egress)
214 {
215  NFD_LOG_DEBUG("onDroppedInterest out=" << egress.getId() << " name=" << interest.getName());
216 }
217 
218 void
219 Strategy::afterNewNextHop(const fib::NextHop& nextHop, const shared_ptr<pit::Entry>& pitEntry)
220 {
221  NFD_LOG_DEBUG("afterNewNextHop pitEntry=" << pitEntry->getName()
222  << " nexthop=" << nextHop.getFace().getId());
223 }
224 
226 Strategy::sendInterest(const Interest& interest, Face& egress, const shared_ptr<pit::Entry>& pitEntry)
227 {
228  if (interest.getTag<lp::PitToken>() != nullptr) {
229  Interest interest2 = interest; // make a copy to preserve tag on original packet
230  interest2.removeTag<lp::PitToken>();
231  return m_forwarder.onOutgoingInterest(interest2, egress, pitEntry);
232  }
233  return m_forwarder.onOutgoingInterest(interest, egress, pitEntry);
234 }
235 
236 bool
237 Strategy::sendData(const Data& data, Face& egress, const shared_ptr<pit::Entry>& pitEntry)
238 {
239  BOOST_ASSERT(pitEntry->getInterest().matchesData(data));
240 
241  shared_ptr<lp::PitToken> pitToken;
242  auto inRecord = pitEntry->getInRecord(egress);
243  if (inRecord != pitEntry->in_end()) {
244  pitToken = inRecord->getInterest().getTag<lp::PitToken>();
245  }
246 
247  // delete the PIT entry's in-record based on egress,
248  // since the Data is sent to the face from which the Interest was received
249  pitEntry->deleteInRecord(egress);
250 
251  if (pitToken != nullptr) {
252  Data data2 = data; // make a copy so each downstream can get a different PIT token
253  data2.setTag(pitToken);
254  return m_forwarder.onOutgoingData(data2, egress);
255  }
256  return m_forwarder.onOutgoingData(data, egress);
257 }
258 
259 void
260 Strategy::sendDataToAll(const Data& data, const shared_ptr<pit::Entry>& pitEntry, const Face& inFace)
261 {
262  std::set<Face*> pendingDownstreams;
263  auto now = time::steady_clock::now();
264 
265  // remember pending downstreams
266  for (const auto& inRecord : pitEntry->getInRecords()) {
267  if (inRecord.getExpiry() > now) {
268  if (inRecord.getFace().getId() == inFace.getId() &&
269  inRecord.getFace().getLinkType() != ndn::nfd::LINK_TYPE_AD_HOC) {
270  continue;
271  }
272  pendingDownstreams.emplace(&inRecord.getFace());
273  }
274  }
275 
276  for (const auto& pendingDownstream : pendingDownstreams) {
277  this->sendData(data, *pendingDownstream, pitEntry);
278  }
279 }
280 
281 void
282 Strategy::sendNacks(const lp::NackHeader& header, const shared_ptr<pit::Entry>& pitEntry,
283  std::initializer_list<const Face*> exceptFaces)
284 {
285  // populate downstreams with all downstreams faces
286  std::unordered_set<Face*> downstreams;
287  std::transform(pitEntry->in_begin(), pitEntry->in_end(),
288  std::inserter(downstreams, downstreams.end()),
289  [] (const auto& inR) { return &inR.getFace(); });
290 
291  // remove excluded faces
292  for (auto exceptFace : exceptFaces) {
293  downstreams.erase(const_cast<Face*>(exceptFace));
294  }
295 
296  // send Nacks
297  for (auto downstream : downstreams) {
298  this->sendNack(header, *downstream, pitEntry);
299  }
300  // warning: don't loop on pitEntry->getInRecords(), because in-record is deleted when sending Nack
301 }
302 
303 const fib::Entry&
304 Strategy::lookupFib(const pit::Entry& pitEntry) const
305 {
306  const Fib& fib = m_forwarder.getFib();
307 
308  const Interest& interest = pitEntry.getInterest();
309  // has forwarding hint?
310  if (interest.getForwardingHint().empty()) {
311  // FIB lookup with Interest name
312  const fib::Entry& fibEntry = fib.findLongestPrefixMatch(pitEntry);
313  NFD_LOG_TRACE("lookupFib noForwardingHint found=" << fibEntry.getPrefix());
314  return fibEntry;
315  }
316 
317  const auto& fh = interest.getForwardingHint();
318  // Forwarding hint should have been stripped by incoming Interest pipeline when reaching producer region
319  BOOST_ASSERT(!m_forwarder.getNetworkRegionTable().isInProducerRegion(fh));
320 
321  const fib::Entry* fibEntry = nullptr;
322  for (const auto& delegation : fh) {
323  fibEntry = &fib.findLongestPrefixMatch(delegation);
324  if (fibEntry->hasNextHops()) {
325  if (fibEntry->getPrefix().empty()) {
326  // in consumer region, return the default route
327  NFD_LOG_TRACE("lookupFib inConsumerRegion found=" << fibEntry->getPrefix());
328  }
329  else {
330  // in default-free zone, use the first delegation that finds a FIB entry
331  NFD_LOG_TRACE("lookupFib delegation=" << delegation << " found=" << fibEntry->getPrefix());
332  }
333  return *fibEntry;
334  }
335  BOOST_ASSERT(fibEntry->getPrefix().empty()); // only ndn:/ FIB entry can have zero nexthop
336  }
337  BOOST_ASSERT(fibEntry != nullptr && fibEntry->getPrefix().empty());
338  return *fibEntry; // only occurs if no delegation finds a FIB nexthop
339 }
340 
341 } // 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:56
FaceId getId() const noexcept
Returns the face ID.
Definition: face.hpp:121
Represents an entry in the FIB.
Definition: fib-entry.hpp:54
bool hasNextHops() const
Definition: fib-entry.hpp:74
const Name & getPrefix() const
Definition: fib-entry.hpp:60
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:61
Represents a nexthop record in a FIB entry.
Definition: fib-nexthop.hpp:37
Face & getFace() const
Definition: fib-nexthop.hpp:46
virtual void onDroppedInterest(const Interest &interest, Face &egress)
Trigger after an Interest is dropped (e.g., for exceeding allowed retransmissions).
Definition: strategy.cpp:213
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:177
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:206
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
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:304
bool sendNack(const lp::NackHeader &header, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send a Nack packet.
Definition: strategy.hpp:333
virtual void afterNewNextHop(const fib::NextHop &nextHop, const shared_ptr< pit::Entry > &pitEntry)
Trigger after a new nexthop is added.
Definition: strategy.cpp:219
pit::OutRecord * sendInterest(const Interest &interest, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send an Interest packet.
Definition: strategy.cpp:226
bool sendData(const Data &data, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send a Data packet.
Definition: strategy.cpp:237
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:260
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:195
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:187
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:62
const Interest & getInterest() const
Definition: pit-entry.hpp:73
Contains information about an Interest toward an outgoing face.
#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