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_WEBSOCKET
58 #include <websocketpp/version.hpp>
59 #endif
60 
61 namespace po = boost::program_options;
62 
63 NFD_LOG_INIT(Main);
64 
65 namespace nfd {
66 
76 class NfdRunner : noncopyable
77 {
78 public:
79  explicit
80  NfdRunner(const std::string& configFile)
81  : m_nfd(configFile, m_nfdKeyChain)
82  , m_configFile(configFile)
83  , m_terminationSignalSet(getGlobalIoService())
84  , m_reloadSignalSet(getGlobalIoService())
85  {
86  m_terminationSignalSet.add(SIGINT);
87  m_terminationSignalSet.add(SIGTERM);
88  m_terminationSignalSet.async_wait(bind(&NfdRunner::terminate, this, _1, _2));
89 
90  m_reloadSignalSet.add(SIGHUP);
91  m_reloadSignalSet.async_wait(bind(&NfdRunner::reload, this, _1, _2));
92  }
93 
94  void
95  initialize()
96  {
97  m_nfd.initialize();
98  }
99 
100  int
101  run()
102  {
103  // Return value: a non-zero value is assigned when either NFD or RIB manager (running in
104  // a separate thread) fails.
105  std::atomic_int retval(0);
106 
107  boost::asio::io_service* const mainIo = &getGlobalIoService();
108  setMainIoService(mainIo);
109  boost::asio::io_service* ribIo = nullptr;
110 
111  // Mutex and conditional variable to implement synchronization between main and RIB manager
112  // threads:
113  // - to block main thread until RIB manager thread starts and initializes ribIo (to allow
114  // stopping it later)
115  std::mutex m;
116  std::condition_variable cv;
117 
118  std::string configFile = this->m_configFile; // c++11 lambda cannot capture member variables
119  boost::thread ribThread([configFile, &retval, &ribIo, mainIo, &cv, &m] {
120  {
121  std::lock_guard<std::mutex> lock(m);
122  ribIo = &getGlobalIoService();
123  BOOST_ASSERT(ribIo != mainIo);
124  setRibIoService(ribIo);
125  }
126  cv.notify_all(); // notify that ribIo has been assigned
127 
128  try {
129  ndn::KeyChain ribKeyChain;
130  // must be created inside a separate thread
131  rib::Service ribService(configFile, ribKeyChain);
132  getGlobalIoService().run(); // ribIo is not thread-safe to use here
133  }
134  catch (const std::exception& e) {
135  NFD_LOG_FATAL(e.what());
136  retval = 1;
137  mainIo->stop();
138  }
139 
140  {
141  std::lock_guard<std::mutex> lock(m);
142  ribIo = nullptr;
143  }
144  });
145 
146  {
147  // Wait to guarantee that ribIo is properly initialized, so it can be used to terminate
148  // RIB manager thread.
149  std::unique_lock<std::mutex> lock(m);
150  cv.wait(lock, [&ribIo] { return ribIo != nullptr; });
151  }
152 
153  try {
154  mainIo->run();
155  }
156  catch (const std::exception& e) {
158  retval = 1;
159  }
160  catch (const PrivilegeHelper::Error& e) {
161  NFD_LOG_FATAL(e.what());
162  retval = 4;
163  }
164 
165  {
166  // ribIo is guaranteed to be alive at this point
167  std::lock_guard<std::mutex> lock(m);
168  if (ribIo != nullptr) {
169  ribIo->stop();
170  ribIo = nullptr;
171  }
172  }
173  ribThread.join();
174 
175  return retval;
176  }
177 
178  void
179  terminate(const boost::system::error_code& error, int signalNo)
180  {
181  if (error)
182  return;
183 
184  NFD_LOG_INFO("Caught signal '" << ::strsignal(signalNo) << "', exiting...");
185  getGlobalIoService().stop();
186  }
187 
188  void
189  reload(const boost::system::error_code& error, int signalNo)
190  {
191  if (error)
192  return;
193 
194  NFD_LOG_INFO("Caught signal '" << ::strsignal(signalNo) << "', reloading...");
195  m_nfd.reloadConfigFile();
196 
197  m_reloadSignalSet.async_wait(bind(&NfdRunner::reload, this, _1, _2));
198  }
199 
200 private:
201  ndn::KeyChain m_nfdKeyChain;
202  Nfd m_nfd;
203  std::string m_configFile;
204 
205  boost::asio::signal_set m_terminationSignalSet;
206  boost::asio::signal_set m_reloadSignalSet;
207 };
208 
209 static void
210 printUsage(std::ostream& os, const char* programName, const po::options_description& opts)
211 {
212  os << "Usage: " << programName << " [options]\n"
213  << "\n"
214  << "Run the NDN Forwarding Daemon (NFD)\n"
215  << "\n"
216  << opts;
217 }
218 
219 static void
220 printLogModules(std::ostream& os)
221 {
222  const auto& modules = ndn::util::Logging::getLoggerNames();
223  std::copy(modules.begin(), modules.end(), ndn::make_ostream_joiner(os, "\n"));
224  os << std::endl;
225 }
226 
227 } // namespace nfd
228 
229 int
230 main(int argc, char** argv)
231 {
232  using namespace nfd;
233 
234  std::string configFile = DEFAULT_CONFIG_FILE;
235 
236  po::options_description description("Options");
237  description.add_options()
238  ("help,h", "print this message and exit")
239  ("version,V", "show version information and exit")
240  ("config,c", po::value<std::string>(&configFile),
241  "path to configuration file (default: " DEFAULT_CONFIG_FILE ")")
242  ("modules,m", "list available logging modules")
243  ;
244 
245  po::variables_map vm;
246  try {
247  po::store(po::parse_command_line(argc, argv, description), vm);
248  po::notify(vm);
249  }
250  catch (const std::exception& e) {
251  // Cannot use NFD_LOG_* macros here, because the logging subsystem is not initialized yet
252  // at this point. Moreover, we don't want to clutter error messages related to command-line
253  // parsing with timestamps and other useless text added by the macros.
254  std::cerr << "ERROR: " << e.what() << "\n\n";
255  printUsage(std::cerr, argv[0], description);
256  return 2;
257  }
258 
259  if (vm.count("help") > 0) {
260  printUsage(std::cout, argv[0], description);
261  return 0;
262  }
263 
264  if (vm.count("version") > 0) {
265  std::cout << NFD_VERSION_BUILD_STRING << std::endl;
266  return 0;
267  }
268 
269  if (vm.count("modules") > 0) {
270  printLogModules(std::cout);
271  return 0;
272  }
273 
274  const std::string boostBuildInfo =
275  "with Boost version " + to_string(BOOST_VERSION / 100000) +
276  "." + to_string(BOOST_VERSION / 100 % 1000) +
277  "." + to_string(BOOST_VERSION % 100);
278  const std::string pcapBuildInfo =
279 #ifdef HAVE_LIBPCAP
280  "with " + std::string(pcap_lib_version());
281 #else
282  "without libpcap";
283 #endif
284  const std::string wsBuildInfo =
285 #ifdef HAVE_WEBSOCKET
286  "with WebSocket++ version " + to_string(websocketpp::major_version) +
287  "." + to_string(websocketpp::minor_version) +
288  "." + to_string(websocketpp::patch_version);
289 #else
290  "without WebSocket++";
291 #endif
292 
293  std::clog << "NFD version " NFD_VERSION_BUILD_STRING " starting\n"
294  << "Built with " BOOST_COMPILER ", with " BOOST_STDLIB
295  ", " << boostBuildInfo <<
296  ", " << pcapBuildInfo <<
297  ", " << wsBuildInfo <<
298  ", with ndn-cxx version " NDN_CXX_VERSION_BUILD_STRING
299  << std::endl;
300 
301  NfdRunner runner(configFile);
302  try {
303  runner.initialize();
304  }
305  catch (const boost::filesystem::filesystem_error& e) {
306  if (e.code() == boost::system::errc::permission_denied) {
307  NFD_LOG_FATAL("Permission denied for " << e.path1() <<
308  ". This program should be run as superuser");
309  return 4;
310  }
311  else {
313  return 1;
314  }
315  }
316  catch (const std::exception& e) {
318  return 1;
319  }
320  catch (const PrivilegeHelper::Error& e) {
321  // PrivilegeHelper::Errors do not inherit from std::exception
322  // and represent seteuid/gid failures
323  NFD_LOG_FATAL(e.what());
324  return 4;
325  }
326 
327  return runner.run();
328 }
std::string getExtendedErrorMessage(const E &exception)
static void printLogModules(std::ostream &os)
Definition: main.cpp:220
int main(int argc, char **argv)
Definition: main.cpp:230
void setMainIoService(boost::asio::io_service *mainIo)
Definition: global-io.cpp:58
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
Definition: algorithm.hpp:32
#define NFD_LOG_INFO
Definition: logger.hpp:39
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
static void printUsage(std::ostream &os, const char *programName, const po::options_description &opts)
Definition: main.cpp:210
#define NFD_LOG_FATAL
Definition: logger.hpp:42
void setRibIoService(boost::asio::io_service *ribIo)
Definition: global-io.cpp:64
boost::asio::io_service & getGlobalIoService()
Definition: global-io.cpp:42