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-2018, 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 
30 #include "core/global-io.hpp"
31 #include "core/logger.hpp"
33 #include "core/version.hpp"
34 
35 #include <string.h> // for strsignal()
36 
37 #include <boost/config.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 // boost::thread is used instead of std::thread to guarantee proper cleanup of thread local storage,
43 // see https://www.boost.org/doc/libs/1_58_0/doc/html/thread/thread_local_storage.html
44 #include <boost/thread.hpp>
45 #include <boost/version.hpp>
46 
47 #include <atomic>
48 #include <condition_variable>
49 #include <iostream>
50 
51 #include <ndn-cxx/util/logging.hpp>
52 #include <ndn-cxx/version.hpp>
53 
54 #ifdef HAVE_LIBPCAP
55 #include <pcap/pcap.h>
56 #endif
57 #ifdef HAVE_SYSTEMD
58 #include <systemd/sd-daemon.h>
59 #endif
60 #ifdef HAVE_WEBSOCKET
61 #include <websocketpp/version.hpp>
62 #endif
63 
64 namespace po = boost::program_options;
65 
67 
68 namespace nfd {
69 
79 class NfdRunner : noncopyable
80 {
81 public:
82  explicit
83  NfdRunner(const std::string& configFile)
84  : m_nfd(configFile, m_nfdKeyChain)
85  , m_configFile(configFile)
86  , m_terminationSignalSet(getGlobalIoService())
87  , m_reloadSignalSet(getGlobalIoService())
88  {
89  m_terminationSignalSet.add(SIGINT);
90  m_terminationSignalSet.add(SIGTERM);
91  m_terminationSignalSet.async_wait(bind(&NfdRunner::terminate, this, _1, _2));
92 
93  m_reloadSignalSet.add(SIGHUP);
94  m_reloadSignalSet.async_wait(bind(&NfdRunner::reload, this, _1, _2));
95  }
96 
97  void
99  {
100  m_nfd.initialize();
101  }
102 
103  int
104  run()
105  {
106  // Return value: a non-zero value is assigned when either NFD or RIB manager (running in
107  // a separate thread) fails.
108  std::atomic_int retval(0);
109 
110  boost::asio::io_service* const mainIo = &getGlobalIoService();
111  setMainIoService(mainIo);
112  boost::asio::io_service* ribIo = nullptr;
113 
114  // Mutex and conditional variable to implement synchronization between main and RIB manager
115  // threads:
116  // - to block main thread until RIB manager thread starts and initializes ribIo (to allow
117  // stopping it later)
118  std::mutex m;
119  std::condition_variable cv;
120 
121  std::string configFile = this->m_configFile; // c++11 lambda cannot capture member variables
122  boost::thread ribThread([configFile, &retval, &ribIo, mainIo, &cv, &m] {
123  {
124  std::lock_guard<std::mutex> lock(m);
125  ribIo = &getGlobalIoService();
126  BOOST_ASSERT(ribIo != mainIo);
127  setRibIoService(ribIo);
128  }
129  cv.notify_all(); // notify that ribIo has been assigned
130 
131  try {
132  ndn::KeyChain ribKeyChain;
133  // must be created inside a separate thread
134  rib::Service ribService(configFile, ribKeyChain);
135  getGlobalIoService().run(); // ribIo is not thread-safe to use here
136  }
137  catch (const std::exception& e) {
138  NFD_LOG_FATAL(e.what());
139  retval = 1;
140  mainIo->stop();
141  }
142 
143  {
144  std::lock_guard<std::mutex> lock(m);
145  ribIo = nullptr;
146  }
147  });
148 
149  {
150  // Wait to guarantee that ribIo is properly initialized, so it can be used to terminate
151  // RIB manager thread.
152  std::unique_lock<std::mutex> lock(m);
153  cv.wait(lock, [&ribIo] { return ribIo != nullptr; });
154  }
155 
156  try {
157  systemdNotify("READY=1");
158  mainIo->run();
159  }
160  catch (const std::exception& e) {
162  retval = 1;
163  }
164  catch (const PrivilegeHelper::Error& e) {
165  NFD_LOG_FATAL(e.what());
166  retval = 4;
167  }
168 
169  {
170  // ribIo is guaranteed to be alive at this point
171  std::lock_guard<std::mutex> lock(m);
172  if (ribIo != nullptr) {
173  ribIo->stop();
174  ribIo = nullptr;
175  }
176  }
177  ribThread.join();
178 
179  return retval;
180  }
181 
182  static void
183  systemdNotify(const char* state)
184  {
185 #ifdef HAVE_SYSTEMD
186  sd_notify(0, state);
187 #endif
188  }
189 
190 private:
191  void
192  terminate(const boost::system::error_code& error, int signalNo)
193  {
194  if (error)
195  return;
196 
197  NFD_LOG_INFO("Caught signal '" << ::strsignal(signalNo) << "', exiting...");
198 
199  systemdNotify("STOPPING=1");
200  getGlobalIoService().stop();
201  }
202 
203  void
204  reload(const boost::system::error_code& error, int signalNo)
205  {
206  if (error)
207  return;
208 
209  NFD_LOG_INFO("Caught signal '" << ::strsignal(signalNo) << "', reloading...");
210 
211  systemdNotify("RELOADING=1");
212  m_nfd.reloadConfigFile();
213  systemdNotify("READY=1");
214 
215  m_reloadSignalSet.async_wait(bind(&NfdRunner::reload, this, _1, _2));
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_terminationSignalSet;
224  boost::asio::signal_set m_reloadSignalSet;
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 = 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: " 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 HAVE_LIBPCAP
298  "with " + std::string(pcap_lib_version());
299 #else
300  "without libpcap";
301 #endif
302  const std::string wsBuildInfo =
303 #ifdef HAVE_WEBSOCKET
304  "with WebSocket++ version " + to_string(websocketpp::major_version) +
305  "." + to_string(websocketpp::minor_version) +
306  "." + to_string(websocketpp::patch_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  if (e.code() == boost::system::errc::permission_denied) {
325  NFD_LOG_FATAL("Permission denied for " << e.path1() <<
326  ". This program should be run as superuser");
327  return 4;
328  }
329  else {
331  return 1;
332  }
333  }
334  catch (const std::exception& e) {
336  return 1;
337  }
338  catch (const PrivilegeHelper::Error& e) {
339  // PrivilegeHelper::Errors do not inherit from std::exception
340  // and represent seteuid/gid failures
341  NFD_LOG_FATAL(e.what());
342  return 4;
343  }
344 
345  return runner.run();
346 }
void initialize()
Definition: main.cpp:98
std::string getExtendedErrorMessage(const E &exception)
static void printLogModules(std::ostream &os)
Definition: main.cpp:238
The interface of signing key management.
Definition: key-chain.hpp:46
initializes and executes NFD-RIB service thread
Definition: service.hpp:51
Main
Definition: main.cpp:66
represents a serious seteuid/gid failure
int main(int argc, char **argv)
Definition: main.cpp:248
detail::SimulatorIo & getGlobalIoService()
Definition: global-io.cpp:48
#define NFD_LOG_INFO
Definition: logger.hpp:39
NfdRunner(const std::string &configFile)
Definition: main.cpp:83
static void systemdNotify(const char *state)
Definition: main.cpp:183
int run()
Definition: main.cpp:104
void reloadConfigFile()
Reload configuration file and apply update (if any)
Definition: nfd.cpp:177
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:40
Nfd
Definition: nfd.cpp:46
ostream_joiner< std::decay_t< DelimT >, CharT, Traits > make_ostream_joiner(std::basic_ostream< CharT, Traits > &os, DelimT &&delimiter)
void initialize()
Perform initialization of NFD instance After initialization, NFD instance can be started by invoking ...
Definition: nfd.cpp:74
#define NFD_LOG_FATAL
Definition: logger.hpp:42
Executes NFD with RIB manager.
Definition: main.cpp:79
static void printUsage(std::ostream &os, const char *programName, const po::options_description &opts)
Definition: main.cpp:228
std::string to_string(const V &v)
Definition: backports.hpp:67
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31