NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
main.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2021, 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 "nfd.hpp"
27 #include "rib/service.hpp"
28 
29 #include "common/global.hpp"
30 #include "common/logger.hpp"
32 #include "core/version.hpp"
33 
34 #include <string.h> // for strsignal()
35 
36 #include <boost/config.hpp>
37 #include <boost/exception/diagnostic_information.hpp>
38 #include <boost/filesystem.hpp>
39 #include <boost/program_options/options_description.hpp>
40 #include <boost/program_options/parsers.hpp>
41 #include <boost/program_options/variables_map.hpp>
42 #include <boost/version.hpp>
43 
44 #include <atomic>
45 #include <condition_variable>
46 #include <iostream>
47 #include <thread>
48 
49 #include <ndn-cxx/util/logging.hpp>
51 #include <ndn-cxx/version.hpp>
52 
53 #ifdef NFD_HAVE_LIBPCAP
54 #include <pcap/pcap.h>
55 #endif
56 #ifdef NFD_HAVE_SYSTEMD
57 #include <systemd/sd-daemon.h>
58 #endif
59 #ifdef NFD_HAVE_WEBSOCKET
60 #include <websocketpp/version.hpp>
61 #endif
62 
63 namespace po = boost::program_options;
64 
66 
67 namespace nfd {
68 
78 class NfdRunner : noncopyable
79 {
80 public:
81  explicit
82  NfdRunner(const std::string& configFile)
83  : m_nfd(configFile, m_nfdKeyChain)
84  , m_configFile(configFile)
85  , m_terminateSignals(getGlobalIoService(), SIGINT, SIGTERM)
86  , m_reloadSignals(getGlobalIoService(), SIGHUP)
87  {
88  m_terminateSignals.async_wait([this] (auto&&... args) {
89  terminate(std::forward<decltype(args)>(args)...);
90  });
91  m_reloadSignals.async_wait([this] (auto&&... args) {
92  reload(std::forward<decltype(args)>(args)...);
93  });
94  }
95 
96  void
98  {
99  m_nfd.initialize();
100  }
101 
102  int
103  run()
104  {
105  // Return value: a non-zero value is assigned when either NFD or RIB manager (running in
106  // a separate thread) fails.
107  std::atomic_int retval(0);
108 
109  boost::asio::io_service* const mainIo = &getGlobalIoService();
110  setMainIoService(mainIo);
111  boost::asio::io_service* ribIo = nullptr;
112 
113  // Mutex and conditional variable to implement synchronization between main and RIB manager
114  // threads:
115  // - to block main thread until RIB manager thread starts and initializes ribIo (to allow
116  // stopping it later)
117  std::mutex m;
118  std::condition_variable cv;
119 
120  std::thread ribThread([configFile = m_configFile, &retval, &ribIo, mainIo, &cv, &m] {
121  {
122  std::lock_guard<std::mutex> lock(m);
123  ribIo = &getGlobalIoService();
124  BOOST_ASSERT(ribIo != mainIo);
125  setRibIoService(ribIo);
126  }
127  cv.notify_all(); // notify that ribIo has been assigned
128 
129  try {
130  ndn::KeyChain ribKeyChain;
131  // must be created inside a separate thread
132  rib::Service ribService(configFile, ribKeyChain);
133  getGlobalIoService().run(); // ribIo is not thread-safe to use here
134  }
135  catch (const std::exception& e) {
136  NFD_LOG_FATAL(boost::diagnostic_information(e));
137  retval = 1;
138  mainIo->stop();
139  }
140 
141  {
142  std::lock_guard<std::mutex> lock(m);
143  ribIo = nullptr;
144  }
145  });
146 
147  {
148  // Wait to guarantee that ribIo is properly initialized, so it can be used to terminate
149  // RIB manager thread.
150  std::unique_lock<std::mutex> lock(m);
151  cv.wait(lock, [&ribIo] { return ribIo != nullptr; });
152  }
153 
154  try {
155  systemdNotify("READY=1");
156  mainIo->run();
157  }
158  catch (const std::exception& e) {
159  NFD_LOG_FATAL(boost::diagnostic_information(e));
160  retval = 1;
161  }
162  catch (const PrivilegeHelper::Error& e) {
163  NFD_LOG_FATAL(e.what());
164  retval = 4;
165  }
166 
167  {
168  // ribIo is guaranteed to be alive at this point
169  std::lock_guard<std::mutex> lock(m);
170  if (ribIo != nullptr) {
171  ribIo->stop();
172  ribIo = nullptr;
173  }
174  }
175  ribThread.join();
176 
177  return retval;
178  }
179 
180  static void
181  systemdNotify(const char* state)
182  {
183 #ifdef NFD_HAVE_SYSTEMD
184  sd_notify(0, state);
185 #endif
186  }
187 
188 private:
189  void
190  terminate(const boost::system::error_code& error, int signalNo)
191  {
192  if (error)
193  return;
194 
195  NFD_LOG_INFO("Caught signal " << signalNo << " (" << ::strsignal(signalNo) << "), exiting...");
196 
197  systemdNotify("STOPPING=1");
198  getGlobalIoService().stop();
199  }
200 
201  void
202  reload(const boost::system::error_code& error, int signalNo)
203  {
204  if (error)
205  return;
206 
207  NFD_LOG_INFO("Caught signal " << signalNo << " (" << ::strsignal(signalNo) << "), reloading...");
208 
209  systemdNotify("RELOADING=1");
210  m_nfd.reloadConfigFile();
211  systemdNotify("READY=1");
212 
213  m_reloadSignals.async_wait([this] (auto&&... args) {
214  reload(std::forward<decltype(args)>(args)...);
215  });
216  }
217 
218 private:
219  ndn::KeyChain m_nfdKeyChain;
220  Nfd m_nfd;
221  std::string m_configFile;
222 
223  boost::asio::signal_set m_terminateSignals;
224  boost::asio::signal_set m_reloadSignals;
225 };
226 
227 static void
228 printUsage(std::ostream& os, const char* programName, const po::options_description& opts)
229 {
230  os << "Usage: " << programName << " [options]\n"
231  << "\n"
232  << "Run the NDN Forwarding Daemon (NFD)\n"
233  << "\n"
234  << opts;
235 }
236 
237 static void
238 printLogModules(std::ostream& os)
239 {
240  const auto& modules = ndn::util::Logging::getLoggerNames();
241  std::copy(modules.begin(), modules.end(), ndn::make_ostream_joiner(os, "\n"));
242  os << std::endl;
243 }
244 
245 } // namespace nfd
246 
247 int
248 main(int argc, char** argv)
249 {
250  using namespace nfd;
251 
252  std::string configFile = NFD_DEFAULT_CONFIG_FILE;
253 
254  po::options_description description("Options");
255  description.add_options()
256  ("help,h", "print this message and exit")
257  ("version,V", "show version information and exit")
258  ("config,c", po::value<std::string>(&configFile),
259  "path to configuration file (default: " NFD_DEFAULT_CONFIG_FILE ")")
260  ("modules,m", "list available logging modules")
261  ;
262 
263  po::variables_map vm;
264  try {
265  po::store(po::parse_command_line(argc, argv, description), vm);
266  po::notify(vm);
267  }
268  catch (const std::exception& e) {
269  // Cannot use NFD_LOG_* macros here, because the logging subsystem is not initialized yet
270  // at this point. Moreover, we don't want to clutter error messages related to command-line
271  // parsing with timestamps and other useless text added by the macros.
272  std::cerr << "ERROR: " << e.what() << "\n\n";
273  printUsage(std::cerr, argv[0], description);
274  return 2;
275  }
276 
277  if (vm.count("help") > 0) {
278  printUsage(std::cout, argv[0], description);
279  return 0;
280  }
281 
282  if (vm.count("version") > 0) {
283  std::cout << NFD_VERSION_BUILD_STRING << std::endl;
284  return 0;
285  }
286 
287  if (vm.count("modules") > 0) {
288  printLogModules(std::cout);
289  return 0;
290  }
291 
292  const std::string boostBuildInfo =
293  "with Boost version " + to_string(BOOST_VERSION / 100000) +
294  "." + to_string(BOOST_VERSION / 100 % 1000) +
295  "." + to_string(BOOST_VERSION % 100);
296  const std::string pcapBuildInfo =
297 #ifdef NFD_HAVE_LIBPCAP
298  "with " + std::string(pcap_lib_version());
299 #else
300  "without libpcap";
301 #endif
302  const std::string wsBuildInfo =
303 #ifdef NFD_HAVE_WEBSOCKET
304  "with WebSocket++ version " + to_string(websocketpp::major_version) +
307 #else
308  "without WebSocket++";
309 #endif
310 
311  std::clog << "NFD version " << NFD_VERSION_BUILD_STRING << " starting\n"
312  << "Built with " BOOST_COMPILER ", with " BOOST_STDLIB
313  ", " << boostBuildInfo <<
314  ", " << pcapBuildInfo <<
315  ", " << wsBuildInfo <<
316  ", with ndn-cxx version " NDN_CXX_VERSION_BUILD_STRING
317  << std::endl;
318 
319  NfdRunner runner(configFile);
320  try {
321  runner.initialize();
322  }
323  catch (const boost::filesystem::filesystem_error& e) {
324  NFD_LOG_FATAL(boost::diagnostic_information(e));
325  return e.code() == boost::system::errc::permission_denied ? 4 : 1;
326  }
327  catch (const std::exception& e) {
328  NFD_LOG_FATAL(boost::diagnostic_information(e));
329  return 1;
330  }
331  catch (const PrivilegeHelper::Error& e) {
332  // PrivilegeHelper::Errors do not inherit from std::exception
333  // and represent seteuid/gid failures
334  NFD_LOG_FATAL(e.what());
335  return 4;
336  }
337 
338  return runner.run();
339 }
void initialize()
Definition: main.cpp:97
static void printLogModules(std::ostream &os)
Definition: main.cpp:238
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
std::string to_string(const T &val)
Definition: backports.hpp:86
initializes and executes NFD-RIB service thread
Definition: service.hpp:52
ndn security KeyChain
Definition: key-chain.cpp:70
represents a serious seteuid/gid failure
int main(int argc, char **argv)
Definition: main.cpp:248
static int const patch_version
Library patch version number.
Definition: version.hpp:47
detail::SimulatorIo & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:49
NfdRunner(const std::string &configFile)
Definition: main.cpp:82
static void systemdNotify(const char *state)
Definition: main.cpp:181
int run()
Definition: main.cpp:103
#define NFD_LOG_INFO
Definition: logger.hpp:39
static int const major_version
Library major version number.
Definition: version.hpp:43
void reloadConfigFile()
Reload configuration file and apply updates (if any).
Definition: nfd.cpp:181
Class representing the NFD instance.
Definition: nfd.hpp:58
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:39
Backport of ostream_joiner from the Library Fundamentals v2 TS.
ostream_joiner< std::decay_t< DelimT >, CharT, Traits > make_ostream_joiner(std::basic_ostream< CharT, Traits > &os, DelimT &&delimiter)
#define NFD_LOG_FATAL
Definition: logger.hpp:42
void initialize()
Perform initialization of NFD instance.
Definition: nfd.cpp:76
static int const minor_version
Library minor version number.
Definition: version.hpp:45
Executes NFD with RIB manager.
Definition: main.cpp:78
static void printUsage(std::ostream &os, const char *programName, const po::options_description &opts)
Definition: main.cpp:228
Main
Definition: main.cpp:65