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-2022, 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/asio/signal_set.hpp>
37 #include <boost/config.hpp>
38 #include <boost/exception/diagnostic_information.hpp>
39 #include <boost/filesystem.hpp>
40 #include <boost/program_options/options_description.hpp>
41 #include <boost/program_options/parsers.hpp>
42 #include <boost/program_options/variables_map.hpp>
43 #include <boost/version.hpp>
44 
45 #include <atomic>
46 #include <condition_variable>
47 #include <iostream>
48 #include <thread>
49 
50 #include <ndn-cxx/util/logging.hpp>
51 #include <ndn-cxx/util/ostream-joiner.hpp>
52 #include <ndn-cxx/version.hpp>
53 
54 #ifdef NFD_HAVE_LIBPCAP
55 #include <pcap/pcap.h>
56 #endif
57 #ifdef NFD_HAVE_SYSTEMD
58 #include <systemd/sd-daemon.h>
59 #endif
60 #ifdef NFD_HAVE_WEBSOCKET
61 #include <websocketpp/version.hpp>
62 #endif
63 
64 namespace po = boost::program_options;
65 
66 NFD_LOG_INIT(Main);
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_terminateSignals(getGlobalIoService(), SIGINT, SIGTERM)
87  , m_reloadSignals(getGlobalIoService(), SIGHUP)
88  {
89  m_terminateSignals.async_wait([this] (auto&&... args) {
90  terminate(std::forward<decltype(args)>(args)...);
91  });
92  m_reloadSignals.async_wait([this] (auto&&... args) {
93  reload(std::forward<decltype(args)>(args)...);
94  });
95  }
96 
97  void
98  initialize()
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::thread ribThread([configFile = m_configFile, &retval, &ribIo, mainIo, &cv, &m] {
122  {
123  std::lock_guard<std::mutex> lock(m);
124  ribIo = &getGlobalIoService();
125  BOOST_ASSERT(ribIo != mainIo);
126  setRibIoService(ribIo);
127  }
128  cv.notify_all(); // notify that ribIo has been assigned
129 
130  try {
131  ndn::KeyChain ribKeyChain;
132  // must be created inside a separate thread
133  rib::Service ribService(configFile, ribKeyChain);
134  getGlobalIoService().run(); // ribIo is not thread-safe to use here
135  }
136  catch (const std::exception& e) {
137  NFD_LOG_FATAL(boost::diagnostic_information(e));
138  retval = 1;
139  mainIo->stop();
140  }
141 
142  {
143  std::lock_guard<std::mutex> lock(m);
144  ribIo = nullptr;
145  }
146  });
147 
148  {
149  // Wait to guarantee that ribIo is properly initialized, so it can be used to terminate
150  // RIB manager thread.
151  std::unique_lock<std::mutex> lock(m);
152  cv.wait(lock, [&ribIo] { return ribIo != nullptr; });
153  }
154 
155  try {
156  systemdNotify("READY=1");
157  mainIo->run();
158  }
159  catch (const std::exception& e) {
160  NFD_LOG_FATAL(boost::diagnostic_information(e));
161  retval = 1;
162  }
163  catch (const PrivilegeHelper::Error& e) {
164  NFD_LOG_FATAL(e.what());
165  retval = 4;
166  }
167 
168  {
169  // ribIo is guaranteed to be alive at this point
170  std::lock_guard<std::mutex> lock(m);
171  if (ribIo != nullptr) {
172  ribIo->stop();
173  ribIo = nullptr;
174  }
175  }
176  ribThread.join();
177 
178  return retval;
179  }
180 
181  static void
182  systemdNotify(const char* state)
183  {
184 #ifdef NFD_HAVE_SYSTEMD
185  sd_notify(0, state);
186 #endif
187  }
188 
189 private:
190  void
191  terminate(const boost::system::error_code& error, int signalNo)
192  {
193  if (error)
194  return;
195 
196  NFD_LOG_INFO("Caught signal " << signalNo << " (" << ::strsignal(signalNo) << "), exiting...");
197 
198  systemdNotify("STOPPING=1");
199  getGlobalIoService().stop();
200  }
201 
202  void
203  reload(const boost::system::error_code& error, int signalNo)
204  {
205  if (error)
206  return;
207 
208  NFD_LOG_INFO("Caught signal " << signalNo << " (" << ::strsignal(signalNo) << "), reloading...");
209 
210  systemdNotify("RELOADING=1");
211  m_nfd.reloadConfigFile();
212  systemdNotify("READY=1");
213 
214  m_reloadSignals.async_wait([this] (auto&&... args) {
215  reload(std::forward<decltype(args)>(args)...);
216  });
217  }
218 
219 private:
220  ndn::KeyChain m_nfdKeyChain;
221  Nfd m_nfd;
222  std::string m_configFile;
223 
224  boost::asio::signal_set m_terminateSignals;
225  boost::asio::signal_set m_reloadSignals;
226 };
227 
228 static void
229 printUsage(std::ostream& os, const char* programName, const po::options_description& opts)
230 {
231  os << "Usage: " << programName << " [options]\n"
232  << "\n"
233  << "Run the NDN Forwarding Daemon (NFD)\n"
234  << "\n"
235  << opts;
236 }
237 
238 static void
239 printLogModules(std::ostream& os)
240 {
241  const auto& modules = ndn::util::Logging::getLoggerNames();
242  std::copy(modules.begin(), modules.end(), ndn::make_ostream_joiner(os, "\n"));
243  os << std::endl;
244 }
245 
246 } // namespace nfd
247 
248 int
249 main(int argc, char** argv)
250 {
251  using namespace nfd;
252 
253  std::string configFile = NFD_DEFAULT_CONFIG_FILE;
254 
255  po::options_description description("Options");
256  description.add_options()
257  ("help,h", "print this message and exit")
258  ("version,V", "show version information and exit")
259  ("config,c", po::value<std::string>(&configFile),
260  "path to configuration file (default: " NFD_DEFAULT_CONFIG_FILE ")")
261  ("modules,m", "list available logging modules")
262  ;
263 
264  po::variables_map vm;
265  try {
266  po::store(po::parse_command_line(argc, argv, description), vm);
267  po::notify(vm);
268  }
269  catch (const std::exception& e) {
270  // Cannot use NFD_LOG_* macros here, because the logging subsystem is not initialized yet
271  // at this point. Moreover, we don't want to clutter error messages related to command-line
272  // parsing with timestamps and other useless text added by the macros.
273  std::cerr << "ERROR: " << e.what() << "\n\n";
274  printUsage(std::cerr, argv[0], description);
275  return 2;
276  }
277 
278  if (vm.count("help") > 0) {
279  printUsage(std::cout, argv[0], description);
280  return 0;
281  }
282 
283  if (vm.count("version") > 0) {
284  std::cout << NFD_VERSION_BUILD_STRING << std::endl;
285  return 0;
286  }
287 
288  if (vm.count("modules") > 0) {
289  printLogModules(std::cout);
290  return 0;
291  }
292 
293  const std::string boostBuildInfo =
294  "with Boost version " + to_string(BOOST_VERSION / 100000) +
295  "." + to_string(BOOST_VERSION / 100 % 1000) +
296  "." + to_string(BOOST_VERSION % 100);
297  const std::string pcapBuildInfo =
298 #ifdef NFD_HAVE_LIBPCAP
299  "with " + std::string(pcap_lib_version());
300 #else
301  "without libpcap";
302 #endif
303  const std::string wsBuildInfo =
304 #ifdef NFD_HAVE_WEBSOCKET
305  "with WebSocket++ version " + to_string(websocketpp::major_version) +
306  "." + to_string(websocketpp::minor_version) +
307  "." + to_string(websocketpp::patch_version);
308 #else
309  "without WebSocket++";
310 #endif
311 
312  std::clog << "NFD version " << NFD_VERSION_BUILD_STRING << " starting\n"
313  << "Built with " BOOST_COMPILER ", with " BOOST_STDLIB
314  ", " << boostBuildInfo <<
315  ", " << pcapBuildInfo <<
316  ", " << wsBuildInfo <<
317  ", with ndn-cxx version " NDN_CXX_VERSION_BUILD_STRING
318  << std::endl;
319 
320  NfdRunner runner(configFile);
321  try {
322  runner.initialize();
323  }
324  catch (const boost::filesystem::filesystem_error& e) {
325  NFD_LOG_FATAL(boost::diagnostic_information(e));
326  return e.code() == boost::system::errc::permission_denied ? 4 : 1;
327  }
328  catch (const std::exception& e) {
329  NFD_LOG_FATAL(boost::diagnostic_information(e));
330  return 1;
331  }
332  catch (const PrivilegeHelper::Error& e) {
333  // PrivilegeHelper::Errors do not inherit from std::exception
334  // and represent seteuid/gid failures
335  NFD_LOG_FATAL(e.what());
336  return 4;
337  }
338 
339  return runner.run();
340 }
int main(int argc, char **argv)
Definition: main.cpp:249
#define NFD_LOG_INFO
Definition: logger.hpp:39
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
#define NFD_LOG_FATAL
Definition: logger.hpp:42
Definition: common.hpp:77
void setMainIoService(boost::asio::io_service *mainIo)
Definition: global.cpp:77
static void printUsage(std::ostream &os, const char *programName, const po::options_description &opts)
Definition: main.cpp:229
boost::asio::io_service & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:36
static void printLogModules(std::ostream &os)
Definition: main.cpp:239
void setRibIoService(boost::asio::io_service *ribIo)
Definition: global.cpp:83
const char NFD_VERSION_BUILD_STRING[]
NFD version string, including git commit information if NFD is build from a specific git commit.