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-2019, 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 HAVE_LIBPCAP
54 #include <pcap/pcap.h>
55 #endif
56 #ifdef HAVE_SYSTEMD
57 #include <systemd/sd-daemon.h>
58 #endif
59 #ifdef 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_terminationSignalSet(getGlobalIoService())
86  , m_reloadSignalSet(getGlobalIoService())
87  {
88  m_terminationSignalSet.add(SIGINT);
89  m_terminationSignalSet.add(SIGTERM);
90  m_terminationSignalSet.async_wait(bind(&NfdRunner::terminate, this, _1, _2));
91 
92  m_reloadSignalSet.add(SIGHUP);
93  m_reloadSignalSet.async_wait(bind(&NfdRunner::reload, this, _1, _2));
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 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_reloadSignalSet.async_wait(bind(&NfdRunner::reload, this, _1, _2));
214  }
215 
216 private:
217  ndn::KeyChain m_nfdKeyChain;
218  Nfd m_nfd;
219  std::string m_configFile;
220 
221  boost::asio::signal_set m_terminationSignalSet;
222  boost::asio::signal_set m_reloadSignalSet;
223 };
224 
225 static void
226 printUsage(std::ostream& os, const char* programName, const po::options_description& opts)
227 {
228  os << "Usage: " << programName << " [options]\n"
229  << "\n"
230  << "Run the NDN Forwarding Daemon (NFD)\n"
231  << "\n"
232  << opts;
233 }
234 
235 static void
236 printLogModules(std::ostream& os)
237 {
238  const auto& modules = ndn::util::Logging::getLoggerNames();
239  std::copy(modules.begin(), modules.end(), ndn::make_ostream_joiner(os, "\n"));
240  os << std::endl;
241 }
242 
243 } // namespace nfd
244 
245 int
246 main(int argc, char** argv)
247 {
248  using namespace nfd;
249 
250  std::string configFile = DEFAULT_CONFIG_FILE;
251 
252  po::options_description description("Options");
253  description.add_options()
254  ("help,h", "print this message and exit")
255  ("version,V", "show version information and exit")
256  ("config,c", po::value<std::string>(&configFile),
257  "path to configuration file (default: " DEFAULT_CONFIG_FILE ")")
258  ("modules,m", "list available logging modules")
259  ;
260 
261  po::variables_map vm;
262  try {
263  po::store(po::parse_command_line(argc, argv, description), vm);
264  po::notify(vm);
265  }
266  catch (const std::exception& e) {
267  // Cannot use NFD_LOG_* macros here, because the logging subsystem is not initialized yet
268  // at this point. Moreover, we don't want to clutter error messages related to command-line
269  // parsing with timestamps and other useless text added by the macros.
270  std::cerr << "ERROR: " << e.what() << "\n\n";
271  printUsage(std::cerr, argv[0], description);
272  return 2;
273  }
274 
275  if (vm.count("help") > 0) {
276  printUsage(std::cout, argv[0], description);
277  return 0;
278  }
279 
280  if (vm.count("version") > 0) {
281  std::cout << NFD_VERSION_BUILD_STRING << std::endl;
282  return 0;
283  }
284 
285  if (vm.count("modules") > 0) {
286  printLogModules(std::cout);
287  return 0;
288  }
289 
290  const std::string boostBuildInfo =
291  "with Boost version " + to_string(BOOST_VERSION / 100000) +
292  "." + to_string(BOOST_VERSION / 100 % 1000) +
293  "." + to_string(BOOST_VERSION % 100);
294  const std::string pcapBuildInfo =
295 #ifdef HAVE_LIBPCAP
296  "with " + std::string(pcap_lib_version());
297 #else
298  "without libpcap";
299 #endif
300  const std::string wsBuildInfo =
301 #ifdef HAVE_WEBSOCKET
302  "with WebSocket++ version " + to_string(websocketpp::major_version) +
303  "." + to_string(websocketpp::minor_version) +
304  "." + to_string(websocketpp::patch_version);
305 #else
306  "without WebSocket++";
307 #endif
308 
309  std::clog << "NFD version " << NFD_VERSION_BUILD_STRING << " starting\n"
310  << "Built with " BOOST_COMPILER ", with " BOOST_STDLIB
311  ", " << boostBuildInfo <<
312  ", " << pcapBuildInfo <<
313  ", " << wsBuildInfo <<
314  ", with ndn-cxx version " NDN_CXX_VERSION_BUILD_STRING
315  << std::endl;
316 
317  NfdRunner runner(configFile);
318  try {
319  runner.initialize();
320  }
321  catch (const boost::filesystem::filesystem_error& e) {
322  NFD_LOG_FATAL(boost::diagnostic_information(e));
323  return e.code() == boost::system::errc::permission_denied ? 4 : 1;
324  }
325  catch (const std::exception& e) {
326  NFD_LOG_FATAL(boost::diagnostic_information(e));
327  return 1;
328  }
329  catch (const PrivilegeHelper::Error& e) {
330  // PrivilegeHelper::Errors do not inherit from std::exception
331  // and represent seteuid/gid failures
332  NFD_LOG_FATAL(e.what());
333  return 4;
334  }
335 
336  return runner.run();
337 }
nfd::NfdRunner
Executes NFD with RIB manager.
Definition: main.cpp:79
NFD_LOG_INFO
#define NFD_LOG_INFO
Definition: logger.hpp:39
global.hpp
nfd::PrivilegeHelper::Error
represents a serious seteuid/gid failure
Definition: privilege-helper.hpp:44
nfd::NfdRunner::run
int run()
Definition: main.cpp:103
NFD_LOG_FATAL
#define NFD_LOG_FATAL
Definition: logger.hpp:42
nfd.hpp
nfd::printLogModules
static void printLogModules(std::ostream &os)
Definition: main.cpp:236
nfd::Nfd
Nfd
Definition: nfd.cpp:46
main
int main(int argc, char **argv)
Definition: main.cpp:246
nfd::Nfd::reloadConfigFile
void reloadConfigFile()
Reload configuration file and apply updates (if any).
Definition: nfd.cpp:179
ndn::make_ostream_joiner
ostream_joiner< std::decay_t< DelimT >, CharT, Traits > make_ostream_joiner(std::basic_ostream< CharT, Traits > &os, DelimT &&delimiter)
Definition: ostream-joiner.hpp:117
Main
Main
Definition: main.cpp:65
nfd::getGlobalIoService
detail::SimulatorIo & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:49
nfd::rib::Service
initializes and executes NFD-RIB service thread
Definition: service.hpp:53
nfd
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:40
ostream-joiner.hpp
Backport of ostream_joiner from the Library Fundamentals v2 TS.
ndn::security::v2::KeyChain
The interface of signing key management.
Definition: key-chain.hpp:47
nfd::NfdRunner::NfdRunner
NfdRunner(const std::string &configFile)
Definition: main.cpp:82
nfd::NfdRunner::systemdNotify
static void systemdNotify(const char *state)
Definition: main.cpp:181
nfd::printUsage
static void printUsage(std::ostream &os, const char *programName, const po::options_description &opts)
Definition: main.cpp:226
privilege-helper.hpp
ndn::to_string
std::string to_string(const T &val)
Definition: backports.hpp:102
nfd::Nfd::initialize
void initialize()
Perform initialization of NFD instance.
Definition: nfd.cpp:76
nfd::NfdRunner::initialize
void initialize()
Definition: main.cpp:97
nfd::PrivilegeHelper::Error::what
const char * what() const
Definition: privilege-helper.hpp:53
service.hpp
NFD_LOG_INIT
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
logger.hpp