NFD: Named Data Networking Forwarding Daemon 24.07-28-gdcc0e6e0
Loading...
Searching...
No Matches
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-2025, 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
36namespace nfd::fw {
37
38NFD_LOG_INIT(Strategy);
39
40Strategy::Registry&
41Strategy::getRegistry()
42{
43 static Registry registry;
44 return registry;
45}
46
47Strategy::Registry::const_iterator
48Strategy::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
85bool
86Strategy::canCreate(const Name& instanceName)
87{
88 return Strategy::find(instanceName) != getRegistry().end();
89}
90
91unique_ptr<Strategy>
92Strategy::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
107bool
108Strategy::areSameType(const Name& instanceNameA, const Name& instanceNameB)
109{
110 return Strategy::find(instanceNameA) == Strategy::find(instanceNameB);
111}
112
113std::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
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
133Name
134Strategy::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
144Strategy::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
174Strategy::~Strategy() = default;
175
176void
177Strategy::onInterestLoop(const Interest& interest, const FaceEndpoint& ingress)
178{
179 lp::Nack nack(interest);
180 nack.setReason(lp::NackReason::DUPLICATE);
181 this->sendNack(nack, ingress.face);
182}
183
184void
185Strategy::afterContentStoreHit(const Data& data, const FaceEndpoint& ingress,
186 const shared_ptr<pit::Entry>& pitEntry)
187{
188 this->sendData(data, ingress.face, pitEntry);
189}
190
191void
192Strategy::beforeSatisfyInterest(const Data&, const FaceEndpoint&, const shared_ptr<pit::Entry>&)
193{
194}
195
196void
197Strategy::afterReceiveData(const Data& data, const FaceEndpoint& ingress,
198 const shared_ptr<pit::Entry>& pitEntry)
199{
200 this->beforeSatisfyInterest(data, ingress, pitEntry);
201 this->sendDataToAll(data, pitEntry, ingress.face);
202}
203
204void
205Strategy::afterReceiveNack(const lp::Nack&, const FaceEndpoint&, const shared_ptr<pit::Entry>&)
206{
207}
208
209void
211{
212}
213
214void
215Strategy::afterNewNextHop(const fib::NextHop& nextHop, const shared_ptr<pit::Entry>& pitEntry)
216{
217 NFD_LOG_DEBUG("afterNewNextHop pitEntry=" << pitEntry->getName()
218 << " nexthop=" << nextHop.getFace().getId());
219}
220
222Strategy::sendInterest(const Interest& interest, Face& egress, const shared_ptr<pit::Entry>& pitEntry)
223{
224 if (interest.getTag<lp::PitToken>() != nullptr) {
225 Interest interest2 = interest; // make a copy to preserve tag on original packet
226 interest2.removeTag<lp::PitToken>();
227 return m_forwarder.onOutgoingInterest(interest2, egress, pitEntry);
228 }
229 return m_forwarder.onOutgoingInterest(interest, egress, pitEntry);
230}
231
232bool
233Strategy::sendData(const Data& data, Face& egress, const shared_ptr<pit::Entry>& pitEntry)
234{
235 BOOST_ASSERT(pitEntry->getInterest().matchesData(data));
236
237 auto inRecord = pitEntry->findInRecord(egress);
238 if (inRecord != pitEntry->in_end()) {
239 auto pitToken = inRecord->getInterest().getTag<lp::PitToken>();
240
241 // delete the PIT entry's in-record based on egress,
242 // since the Data is sent to the face from which the Interest was received
243 pitEntry->deleteInRecord(inRecord);
244
245 if (pitToken != nullptr) {
246 Data data2 = data; // make a copy so each downstream can get a different PIT token
247 data2.setTag(pitToken);
248 return m_forwarder.onOutgoingData(data2, egress);
249 }
250 }
251 return m_forwarder.onOutgoingData(data, egress);
252}
253
254void
255Strategy::sendDataToAll(const Data& data, const shared_ptr<pit::Entry>& pitEntry, const Face& inFace)
256{
257 std::set<Face*> pendingDownstreams;
258 auto now = time::steady_clock::now();
259
260 // remember pending downstreams
261 for (const auto& inRecord : pitEntry->getInRecords()) {
262 if (inRecord.getExpiry() > now) {
263 if (inRecord.getFace().getId() == inFace.getId() &&
264 inRecord.getFace().getLinkType() != ndn::nfd::LINK_TYPE_AD_HOC) {
265 continue;
266 }
267 pendingDownstreams.emplace(&inRecord.getFace());
268 }
269 }
270
271 for (const auto& pendingDownstream : pendingDownstreams) {
272 this->sendData(data, *pendingDownstream, pitEntry);
273 }
274}
275
276void
277Strategy::sendNacks(const lp::NackHeader& header, const shared_ptr<pit::Entry>& pitEntry,
278 std::initializer_list<const Face*> exceptFaces)
279{
280 // populate downstreams with all downstreams faces
281 std::unordered_set<Face*> downstreams;
282 std::transform(pitEntry->in_begin(), pitEntry->in_end(),
283 std::inserter(downstreams, downstreams.end()),
284 [] (const auto& inR) { return &inR.getFace(); });
285
286 // remove excluded faces
287 for (auto exceptFace : exceptFaces) {
288 downstreams.erase(const_cast<Face*>(exceptFace));
289 }
290
291 // send Nacks
292 for (auto downstream : downstreams) {
293 this->sendNack(header, *downstream, pitEntry);
294 }
295 // warning: don't loop on pitEntry->getInRecords(), because in-record is deleted when sending Nack
296}
297
298const fib::Entry&
299Strategy::lookupFib(const pit::Entry& pitEntry) const
300{
301 const Fib& fib = m_forwarder.getFib();
302
303 const Interest& interest = pitEntry.getInterest();
304 // has forwarding hint?
305 if (interest.getForwardingHint().empty()) {
306 // FIB lookup with Interest name
307 const fib::Entry& fibEntry = fib.findLongestPrefixMatch(pitEntry);
308 NFD_LOG_TRACE("lookupFib no-forwarding-hint found=" << fibEntry.getPrefix());
309 return fibEntry;
310 }
311
312 const auto& fh = interest.getForwardingHint();
313 // Forwarding hint should have been stripped by incoming Interest pipeline when reaching producer region
314 BOOST_ASSERT(!m_forwarder.getNetworkRegionTable().isInProducerRegion(fh));
315
316 const fib::Entry* fibEntry = nullptr;
317 for (const auto& delegation : fh) {
318 fibEntry = &fib.findLongestPrefixMatch(delegation);
319 if (fibEntry->hasNextHops()) {
320 if (fibEntry->getPrefix().empty()) {
321 // in consumer region, return the default route
322 NFD_LOG_TRACE("lookupFib in-consumer-region found=" << fibEntry->getPrefix());
323 }
324 else {
325 // in default-free zone, use the first delegation that finds a FIB entry
326 NFD_LOG_TRACE("lookupFib delegation=" << delegation << " found=" << fibEntry->getPrefix());
327 }
328 return *fibEntry;
329 }
330 BOOST_ASSERT(fibEntry->getPrefix().empty()); // only ndn:/ FIB entry can have zero nexthop
331 }
332 BOOST_ASSERT(fibEntry != nullptr && fibEntry->getPrefix().empty());
333 return *fibEntry; // only occurs if no delegation finds a FIB nexthop
334}
335
336} // 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
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
const Name & getPrefix() const noexcept
Definition fib-entry.hpp:97
bool hasNextHops() const noexcept
Returns whether this Entry has any NextHop records.
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:210
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:185
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:205
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:277
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:299
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:215
pit::OutRecord * sendInterest(const Interest &interest, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send an Interest packet.
Definition strategy.cpp:222
bool sendData(const Data &data, Face &egress, const shared_ptr< pit::Entry > &pitEntry)
Send a Data packet.
Definition strategy.cpp:233
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:255
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:197
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:192
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).
const Interest & getInterest() const
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