rib-manager.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2020, 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 "rib-manager.hpp"
27 
28 #include "common/global.hpp"
29 #include "common/logger.hpp"
30 #include "rib/rib.hpp"
31 #include "table/fib.hpp"
32 
33 #include <ndn-cxx/lp/tags.hpp>
34 #include <ndn-cxx/mgmt/nfd/face-status.hpp>
35 #include <ndn-cxx/mgmt/nfd/rib-entry.hpp>
36 #include <ndn-cxx/security/certificate-fetcher-direct-fetch.hpp>
37 
38 namespace nfd {
39 
40 using rib::RibUpdate;
41 using rib::Route;
42 
43 NFD_LOG_INIT(RibManager);
44 
45 static const std::string MGMT_MODULE_NAME = "rib";
46 static const Name LOCALHOST_TOP_PREFIX = "/localhost/nfd";
47 static const time::seconds ACTIVE_FACE_FETCH_INTERVAL = 5_min;
48 
49 const Name RibManager::LOCALHOP_TOP_PREFIX = "/localhop/nfd";
50 
51 RibManager::RibManager(rib::Rib& rib, ndn::Face& face, ndn::KeyChain& keyChain,
52  ndn::nfd::Controller& nfdController, Dispatcher& dispatcher)
53  : ManagerBase(MGMT_MODULE_NAME, dispatcher)
54  , m_rib(rib)
55  , m_keyChain(keyChain)
56  , m_nfdController(nfdController)
57  , m_dispatcher(dispatcher)
58  , m_faceMonitor(face)
59  , m_localhostValidator(face)
60  , m_localhopValidator(make_unique<ndn::security::CertificateFetcherDirectFetch>(face))
61  , m_paValidator(make_unique<ndn::security::CertificateFetcherDirectFetch>(face))
62  , m_isLocalhopEnabled(false)
63 {
64  registerCommandHandler<ndn::nfd::RibRegisterCommand>("register",
65  bind(&RibManager::registerEntry, this, _2, _3, _4, _5));
66  registerCommandHandler<ndn::nfd::RibUnregisterCommand>("unregister",
67  bind(&RibManager::unregisterEntry, this, _2, _3, _4, _5));
68 
69  registerStatusDatasetHandler("list", bind(&RibManager::listEntries, this, _1, _2, _3));
70 }
71 
72 void
73 RibManager::applyLocalhostConfig(const ConfigSection& section, const std::string& filename)
74 {
75  m_localhostValidator.load(section, filename);
76 }
77 
78 void
79 RibManager::enableLocalhop(const ConfigSection& section, const std::string& filename)
80 {
81  m_localhopValidator.load(section, filename);
82  m_isLocalhopEnabled = true;
83 }
84 
85 void
87 {
88  m_isLocalhopEnabled = false;
89 }
90 
91 void
92 RibManager::applyPaConfig(const ConfigSection& section, const std::string& filename)
93 {
94  m_paValidator.load(section, filename);
95 }
96 
97 void
99 {
100  registerTopPrefix(LOCALHOST_TOP_PREFIX);
101 
102  if (m_isLocalhopEnabled) {
103  registerTopPrefix(LOCALHOP_TOP_PREFIX);
104  }
105 
106  NFD_LOG_INFO("Start monitoring face create/destroy events");
107  m_faceMonitor.onNotification.connect(bind(&RibManager::onNotification, this, _1));
108  m_faceMonitor.start();
109 
110  scheduleActiveFaceFetch(ACTIVE_FACE_FETCH_INTERVAL);
111 }
112 
113 void
115 {
116  m_nfdController.start<ndn::nfd::FaceUpdateCommand>(
117  ControlParameters().setFlagBit(ndn::nfd::BIT_LOCAL_FIELDS_ENABLED, true),
118  [] (const ControlParameters&) {
119  NFD_LOG_DEBUG("Local fields enabled");
120  },
121  [] (const ControlResponse& res) {
122  NDN_THROW(Error("Couldn't enable local fields (" + to_string(res.getCode()) +
123  " " + res.getText() + ")"));
124  });
125 }
126 
127 void
128 RibManager::beginAddRoute(const Name& name, Route route, optional<time::nanoseconds> expires,
129  const std::function<void(RibUpdateResult)>& done)
130 {
131  if (expires) {
132  route.expires = time::steady_clock::now() + *expires;
133  }
134  else if (route.expires) {
135  expires = *route.expires - time::steady_clock::now();
136  }
137 
138  if (expires && *expires <= 0_s) {
139  m_rib.onRouteExpiration(name, route);
140  return done(RibUpdateResult::EXPIRED);
141  }
142 
143  NFD_LOG_INFO("Adding route " << name << " nexthop=" << route.faceId <<
144  " origin=" << route.origin << " cost=" << route.cost);
145 
146  if (expires) {
147  auto event = getScheduler().schedule(*expires, [=] { m_rib.onRouteExpiration(name, route); });
148  route.setExpirationEvent(event);
149  NFD_LOG_TRACE("Scheduled unregistration at: " << *route.expires);
150  }
151 
152  RibUpdate update;
154  .setName(name)
155  .setRoute(route);
156  beginRibUpdate(update, done);
157 }
158 
159 void
160 RibManager::beginRemoveRoute(const Name& name, const Route& route,
161  const std::function<void(RibUpdateResult)>& done)
162 {
163  NFD_LOG_INFO("Removing route " << name << " nexthop=" << route.faceId <<
164  " origin=" << route.origin);
165 
166  RibUpdate update;
168  .setName(name)
169  .setRoute(route);
170  beginRibUpdate(update, done);
171 }
172 
173 void
174 RibManager::beginRibUpdate(const RibUpdate& update,
175  const std::function<void(RibUpdateResult)>& done)
176 {
177  m_rib.beginApplyUpdate(update,
178  [=] {
179  NFD_LOG_DEBUG("RIB update succeeded for " << update);
180  done(RibUpdateResult::OK);
181  },
182  [=] (uint32_t code, const std::string& error) {
183  NFD_LOG_DEBUG("RIB update failed for " << update << " (" << code << " " << error << ")");
184 
185  // Since the FIB rejected the update, clean up invalid routes
186  scheduleActiveFaceFetch(1_s);
187 
188  done(RibUpdateResult::ERROR);
189  });
190 }
191 
192 void
193 RibManager::registerTopPrefix(const Name& topPrefix)
194 {
195  // add FIB nexthop
196  m_nfdController.start<ndn::nfd::FibAddNextHopCommand>(
197  ControlParameters().setName(Name(topPrefix).append(MGMT_MODULE_NAME))
198  .setFaceId(0),
199  [=] (const ControlParameters& res) {
200  NFD_LOG_DEBUG("Successfully registered " << topPrefix << " with NFD");
201 
202  // Routes must be inserted into the RIB so route flags can be applied
203  Route route;
204  route.faceId = res.getFaceId();
205  route.origin = ndn::nfd::ROUTE_ORIGIN_APP;
206  route.flags = ndn::nfd::ROUTE_FLAG_CHILD_INHERIT;
207 
208  m_rib.insert(topPrefix, route);
209  },
210  [=] (const ControlResponse& res) {
211  NDN_THROW(Error("Cannot add FIB entry " + topPrefix.toUri() + " (" +
212  to_string(res.getCode()) + " " + res.getText() + ")"));
213  });
214 
215  // add top prefix to the dispatcher without prefix registration
216  m_dispatcher.addTopPrefix(topPrefix, false);
217 }
218 
219 void
220 RibManager::registerEntry(const Name& topPrefix, const Interest& interest,
221  ControlParameters parameters,
222  const ndn::mgmt::CommandContinuation& done)
223 {
224  if (parameters.getName().size() > Fib::getMaxDepth()) {
225  done(ControlResponse(414, "Route prefix cannot exceed " + to_string(Fib::getMaxDepth()) +
226  " components"));
227  return;
228  }
229 
230  setFaceForSelfRegistration(interest, parameters);
231 
232  // Respond since command is valid and authorized
233  done(ControlResponse(200, "Success").setBody(parameters.wireEncode()));
234 
235  Route route;
236  route.faceId = parameters.getFaceId();
237  route.origin = parameters.getOrigin();
238  route.cost = parameters.getCost();
239  route.flags = parameters.getFlags();
240 
241  optional<time::nanoseconds> expires;
242  if (parameters.hasExpirationPeriod() &&
243  parameters.getExpirationPeriod() != time::milliseconds::max()) {
244  expires = time::duration_cast<time::nanoseconds>(parameters.getExpirationPeriod());
245  }
246 
247  beginAddRoute(parameters.getName(), std::move(route), expires, [] (RibUpdateResult) {});
248 }
249 
250 void
251 RibManager::unregisterEntry(const Name& topPrefix, const Interest& interest,
252  ControlParameters parameters,
253  const ndn::mgmt::CommandContinuation& done)
254 {
255  setFaceForSelfRegistration(interest, parameters);
256 
257  // Respond since command is valid and authorized
258  done(ControlResponse(200, "Success").setBody(parameters.wireEncode()));
259 
260  Route route;
261  route.faceId = parameters.getFaceId();
262  route.origin = parameters.getOrigin();
263 
264  beginRemoveRoute(parameters.getName(), route, [] (RibUpdateResult) {});
265 }
266 
267 void
268 RibManager::listEntries(const Name& topPrefix, const Interest& interest,
269  ndn::mgmt::StatusDatasetContext& context)
270 {
271  auto now = time::steady_clock::now();
272  for (const auto& kv : m_rib) {
273  const rib::RibEntry& entry = *kv.second;
274  ndn::nfd::RibEntry item;
275  item.setName(entry.getName());
276  for (const Route& route : entry.getRoutes()) {
277  ndn::nfd::Route r;
278  r.setFaceId(route.faceId);
279  r.setOrigin(route.origin);
280  r.setCost(route.cost);
281  r.setFlags(route.flags);
282  if (route.expires) {
283  r.setExpirationPeriod(time::duration_cast<time::milliseconds>(*route.expires - now));
284  }
285  item.addRoute(r);
286  }
287  context.append(item.wireEncode());
288  }
289  context.end();
290 }
291 
292 void
293 RibManager::setFaceForSelfRegistration(const Interest& request, ControlParameters& parameters)
294 {
295  bool isSelfRegistration = (parameters.getFaceId() == 0);
296  if (isSelfRegistration) {
297  shared_ptr<lp::IncomingFaceIdTag> incomingFaceIdTag = request.getTag<lp::IncomingFaceIdTag>();
298  // NDNLPv2 says "application MUST be prepared to receive a packet without IncomingFaceId field",
299  // but it's fine to assert IncomingFaceId is available, because InternalFace lives inside NFD
300  // and is initialized synchronously with IncomingFaceId field enabled.
301  BOOST_ASSERT(incomingFaceIdTag != nullptr);
302  parameters.setFaceId(*incomingFaceIdTag);
303  }
304 }
305 
306 ndn::mgmt::Authorization
307 RibManager::makeAuthorization(const std::string& verb)
308 {
309  return [this] (const Name& prefix, const Interest& interest,
310  const ndn::mgmt::ControlParameters* params,
311  const ndn::mgmt::AcceptContinuation& accept,
312  const ndn::mgmt::RejectContinuation& reject) {
313  BOOST_ASSERT(params != nullptr);
314  BOOST_ASSERT(typeid(*params) == typeid(ndn::nfd::ControlParameters));
315  BOOST_ASSERT(prefix == LOCALHOST_TOP_PREFIX || prefix == LOCALHOP_TOP_PREFIX);
316 
317  auto& validator = prefix == LOCALHOST_TOP_PREFIX ? m_localhostValidator : m_localhopValidator;
318  validator.validate(interest,
319  bind([&interest, this, accept] { extractRequester(interest, accept); }),
320  bind([reject] { reject(ndn::mgmt::RejectReply::STATUS403); }));
321  };
322 }
323 
324 std::ostream&
326 {
327  switch (res) {
329  return os << "OK";
331  return os << "ERROR";
333  return os << "VALIDATION_FAILURE";
335  return os << "EXPIRED";
337  return os << "NOT_FOUND";
338  }
339  NDN_THROW(std::invalid_argument("Unknown SlAnnounceResult"));
340 }
341 
343 RibManager::getSlAnnounceResultFromRibUpdateResult(RibUpdateResult r)
344 {
345  switch (r) {
346  case RibUpdateResult::OK:
347  return SlAnnounceResult::OK;
348  case RibUpdateResult::ERROR:
350  case RibUpdateResult::EXPIRED:
352  }
353  NDN_CXX_UNREACHABLE;
354 }
355 
356 void
357 RibManager::slAnnounce(const ndn::PrefixAnnouncement& pa, uint64_t faceId,
358  time::milliseconds maxLifetime, const SlAnnounceCallback& cb)
359 {
360  BOOST_ASSERT(pa.getData());
361 
362  m_paValidator.validate(*pa.getData(),
363  [=] (const Data&) {
364  Route route(pa, faceId);
365  route.expires = std::min(route.annExpires, time::steady_clock::now() + maxLifetime);
366  beginAddRoute(pa.getAnnouncedName(), route, nullopt,
367  [=] (RibUpdateResult ribRes) {
368  auto res = getSlAnnounceResultFromRibUpdateResult(ribRes);
369  NFD_LOG_INFO("slAnnounce " << pa.getAnnouncedName() << " " << faceId << ": " << res);
370  cb(res);
371  });
372  },
373  [=] (const Data&, ndn::security::ValidationError err) {
374  NFD_LOG_INFO("slAnnounce " << pa.getAnnouncedName() << " " << faceId <<
375  " validation error: " << err);
377  }
378  );
379 }
380 
381 void
382 RibManager::slRenew(const Name& name, uint64_t faceId, time::milliseconds maxLifetime,
383  const SlAnnounceCallback& cb)
384 {
385  Route routeQuery;
386  routeQuery.faceId = faceId;
387  routeQuery.origin = ndn::nfd::ROUTE_ORIGIN_PREFIXANN;
388  Route* oldRoute = m_rib.findLongestPrefix(name, routeQuery);
389 
390  if (oldRoute == nullptr || !oldRoute->announcement) {
391  NFD_LOG_DEBUG("slRenew " << name << " " << faceId << ": not found");
392  return cb(SlAnnounceResult::NOT_FOUND);
393  }
394  Name routeName = oldRoute->announcement->getAnnouncedName();
395 
396  Route route = *oldRoute;
397  route.expires = std::min(route.annExpires, time::steady_clock::now() + maxLifetime);
398  beginAddRoute(routeName, route, nullopt,
399  [=] (RibUpdateResult ribRes) {
400  auto res = getSlAnnounceResultFromRibUpdateResult(ribRes);
401  NFD_LOG_INFO("slRenew " << name << " " << faceId << ": " << res << " " << routeName);
402  cb(res);
403  });
404 }
405 
406 void
407 RibManager::slFindAnn(const Name& name, const SlFindAnnCallback& cb) const
408 {
409  shared_ptr<rib::RibEntry> entry;
410  auto exactMatch = m_rib.find(name);
411  if (exactMatch != m_rib.end()) {
412  entry = exactMatch->second;
413  }
414  else {
415  entry = m_rib.findParent(name);
416  }
417  if (entry == nullptr) {
418  return cb(nullopt);
419  }
420 
421  auto pa = entry->getPrefixAnnouncement();
422  pa.toData(m_keyChain);
423  cb(pa);
424 }
425 
426 void
427 RibManager::fetchActiveFaces()
428 {
429  NFD_LOG_DEBUG("Fetching active faces");
430 
431  m_nfdController.fetch<ndn::nfd::FaceDataset>(
432  bind(&RibManager::removeInvalidFaces, this, _1),
433  bind(&RibManager::onFetchActiveFacesFailure, this, _1, _2),
434  ndn::nfd::CommandOptions());
435 }
436 
437 void
438 RibManager::onFetchActiveFacesFailure(uint32_t code, const std::string& reason)
439 {
440  NFD_LOG_DEBUG("Face Status Dataset request failure " << code << " " << reason);
441  scheduleActiveFaceFetch(ACTIVE_FACE_FETCH_INTERVAL);
442 }
443 
444 void
445 RibManager::scheduleActiveFaceFetch(const time::seconds& timeToWait)
446 {
447  m_activeFaceFetchEvent = getScheduler().schedule(timeToWait, [this] { fetchActiveFaces(); });
448 }
449 
450 void
451 RibManager::removeInvalidFaces(const std::vector<ndn::nfd::FaceStatus>& activeFaces)
452 {
453  NFD_LOG_DEBUG("Checking for invalid face registrations");
454 
455  std::set<uint64_t> activeFaceIds;
456  for (const auto& faceStatus : activeFaces) {
457  activeFaceIds.insert(faceStatus.getFaceId());
458  }
459  getGlobalIoService().post([=] { m_rib.beginRemoveFailedFaces(activeFaceIds); });
460 
461  // Reschedule the check for future clean up
462  scheduleActiveFaceFetch(ACTIVE_FACE_FETCH_INTERVAL);
463 }
464 
465 void
466 RibManager::onNotification(const ndn::nfd::FaceEventNotification& notification)
467 {
468  NFD_LOG_TRACE("onNotification: " << notification);
469 
470  if (notification.getKind() == ndn::nfd::FACE_EVENT_DESTROYED) {
471  NFD_LOG_DEBUG("Received notification for destroyed FaceId " << notification.getFaceId());
472  getGlobalIoService().post([this, id = notification.getFaceId()] { m_rib.beginRemoveFace(id); });
473  }
474 }
475 
476 } // namespace nfd
const_iterator end() const
Definition: rib.hpp:85
void registerStatusDatasetHandler(const std::string &verb, const ndn::mgmt::StatusDatasetHandler &handler)
Copyright (c) 2014-2017, Regents of the University of California, Arizona Board of Regents...
Definition: dns-srv.cpp:41
uint64_t faceId
Definition: route.hpp:81
RibUpdate & setRoute(const Route &route)
Definition: rib-update.hpp:107
uint64_t cost
Definition: route.hpp:83
represents the Routing Information Base
Definition: rib.hpp:59
shared_ptr< RibEntry > findParent(const Name &prefix) const
Definition: rib.cpp:215
void disableLocalhop()
Disallow accepting commands on /localhop/nfd/rib prefix.
Definition: rib-manager.cpp:86
std::function< void(SlAnnounceResult res)> SlAnnounceCallback
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.
optional< ndn::PrefixAnnouncement > announcement
The prefix announcement that caused the creation of this route.
Definition: route.hpp:91
RibUpdate & setAction(Action action)
Definition: rib-update.hpp:81
Route * findLongestPrefix(const Name &prefix, const Route &route) const
Definition: rib.cpp:78
#define NFD_LOG_TRACE
Definition: logger.hpp:37
void enableLocalhop(const ConfigSection &section, const std::string &filename)
Apply localhop_security configuration and allow accepting commands on /localhop/nfd/rib prefix...
Definition: rib-manager.cpp:79
const Name & getName() const
Definition: rib-entry.hpp:223
void setName(const Name &prefix)
Definition: rib-entry.hpp:217
RibManager(rib::Rib &rib, ndn::Face &face, ndn::KeyChain &keyChain, ndn::nfd::Controller &nfdController, Dispatcher &dispatcher)
Definition: rib-manager.cpp:51
std::function< void(optional< ndn::PrefixAnnouncement >)> SlFindAnnCallback
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.
the announcement cannot be verified against the trust schema
void applyLocalhostConfig(const ConfigSection &section, const std::string &filename)
Apply localhost_security configuration.
Definition: rib-manager.cpp:73
Scheduler & getScheduler()
Returns the global Scheduler instance for the calling thread.
Definition: global.cpp:45
RibUpdate & setName(const Name &name)
Definition: rib-update.hpp:94
void setExpirationEvent(const scheduler::EventId &eid)
Definition: route.hpp:63
A collection of common functions shared by all NFD managers, such as communicating with the dispatche...
const RouteList & getRoutes() const
Definition: rib-entry.hpp:247
void registerWithNfd()
Start accepting commands and dataset requests.
Definition: rib-manager.cpp:98
boost::property_tree::ptree ConfigSection
a config file section
Definition: config-file.hpp:37
std::ostream & operator<<(std::ostream &os, const Network &network)
Definition: network.cpp:79
optional< time::steady_clock::TimePoint > expires
Definition: route.hpp:85
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
Definition: algorithm.hpp:32
void slFindAnn(const Name &name, const SlFindAnnCallback &cb) const
Retrieve an outgoing prefix announcement for self-learning strategy.
void applyPaConfig(const ConfigSection &section, const std::string &filename)
Apply prefix_announcement_validation configuration.
Definition: rib-manager.cpp:92
static const std::string MGMT_MODULE_NAME
Definition: rib-manager.cpp:45
time::steady_clock::TimePoint annExpires
Expiration time of the prefix announcement.
Definition: route.hpp:101
ndn::nfd::RouteOrigin origin
Definition: route.hpp:82
void insert(const Name &prefix, const Route &route)
Definition: rib.cpp:92
represents a route for a name prefix
Definition: route.hpp:43
static const time::seconds ACTIVE_FACE_FETCH_INTERVAL
Definition: rib-manager.cpp:47
static constexpr size_t getMaxDepth()
Maximum number of components in a FIB entry prefix.
Definition: fib.hpp:88
void extractRequester(const Interest &interest, ndn::mgmt::AcceptContinuation accept)
Extracts the requester from a ControlCommand request.
static const Name LOCALHOP_TOP_PREFIX
#define NFD_LOG_INFO
Definition: logger.hpp:39
#define NFD_LOG_DEBUG
Definition: logger.hpp:38
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
Represents a RIB entry, which contains one or more Routes with the same prefix.
Definition: rib-entry.hpp:38
void beginRemoveFace(uint64_t faceId)
starts the FIB update process when a face has been destroyed
Definition: rib.cpp:363
void enableLocalFields()
Enable NDNLP IncomingFaceId field in order to support self-registration commands. ...
RIB and FIB have been updated.
the announcement has expired
void onRouteExpiration(const Name &prefix, const Route &route)
Definition: rib.cpp:202
const_iterator find(const Name &prefix) const
Definition: rib.cpp:55
void beginRemoveFailedFaces(const std::set< uint64_t > &activeFaceIds)
Definition: rib.cpp:373
std::underlying_type_t< ndn::nfd::RouteFlags > flags
Definition: route.hpp:84
void beginApplyUpdate(const RibUpdate &update, const UpdateSuccessCallback &onSuccess, const UpdateFailureCallback &onFailure)
passes the provided RibUpdateBatch to FibUpdater to calculate and send FibUpdates.
Definition: rib.cpp:351
static const Name LOCALHOST_TOP_PREFIX
Definition: rib-manager.cpp:46
route does not exist (slRenew only)
boost::asio::io_service & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:36