Kea  1.5.0
dhcp4/main.cc
Go to the documentation of this file.
1 // Copyright (C) 2011-2018 Internet Systems Consortium, Inc. ("ISC")
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 
7 #include <config.h>
8 #include <kea_version.h>
9 
10 #include <dhcp4/ctrl_dhcp4_srv.h>
11 #include <dhcp4/dhcp4_log.h>
12 #include <dhcp4/parser_context.h>
14 #include <cc/command_interpreter.h>
15 #include <dhcpsrv/cfgmgr.h>
16 #include <log/logger_support.h>
17 #include <log/logger_manager.h>
18 #include <cfgrpt/config_report.h>
19 
20 #include <boost/lexical_cast.hpp>
21 
22 #include <iostream>
23 
24 using namespace isc::data;
25 using namespace isc::dhcp;
26 using namespace isc::process;
27 using namespace std;
28 
34 
35 namespace {
36 
37 const char* const DHCP4_NAME = "kea-dhcp4";
38 
42 void
43 usage() {
44  cerr << "Kea DHCPv4 server, version " << VERSION << endl;
45  cerr << endl;
46  cerr << "Usage: " << DHCP4_NAME
47  << " -[v|V|W] [-d] [-{c|t} cfgfile] [-p number]" << endl;
48  cerr << " -v: print version number and exit" << endl;
49  cerr << " -V: print extended version and exit" << endl;
50  cerr << " -W: display the configuration report and exit" << endl;
51  cerr << " -d: debug mode with extra verbosity (former -v)" << endl;
52  cerr << " -c file: specify configuration file" << endl;
53  cerr << " -t file: check the configuration file syntax and exit" << endl;
54  cerr << " -p number: specify non-standard port number 1-65535 "
55  << "(useful for testing only)" << endl;
56  exit(EXIT_FAILURE);
57 }
58 } // end of anonymous namespace
59 
60 int
61 main(int argc, char* argv[]) {
62  int ch;
63  int port_number = DHCP4_SERVER_PORT; // The default. any other values are
64  // useful for testing only.
65  bool verbose_mode = false; // Should server be verbose?
66  bool check_mode = false; // Check syntax
67 
68  // The standard config file
69  std::string config_file("");
70 
71  while ((ch = getopt(argc, argv, "dvVWc:p:t:")) != -1) {
72  switch (ch) {
73  case 'd':
74  verbose_mode = true;
75  break;
76 
77  case 'v':
78  cout << Dhcpv4Srv::getVersion(false) << endl;
79  return (EXIT_SUCCESS);
80 
81  case 'V':
82  cout << Dhcpv4Srv::getVersion(true) << endl;
83  return (EXIT_SUCCESS);
84 
85  case 'W':
86  cout << isc::detail::getConfigReport() << endl;
87  return (EXIT_SUCCESS);
88 
89  case 't':
90  check_mode = true;
91  // falls through
92 
93  case 'c': // config file
94  config_file = optarg;
95  break;
96 
97  case 'p':
98  try {
99  port_number = boost::lexical_cast<int>(optarg);
100  } catch (const boost::bad_lexical_cast &) {
101  cerr << "Failed to parse port number: [" << optarg
102  << "], 1-65535 allowed." << endl;
103  usage();
104  }
105  if (port_number <= 0 || port_number > 65535) {
106  cerr << "Failed to parse port number: [" << optarg
107  << "], 1-65535 allowed." << endl;
108  usage();
109  }
110  break;
111 
112  default:
113  usage();
114  }
115  }
116 
117  // Check for extraneous parameters.
118  if (argc > optind) {
119  usage();
120  }
121 
122 
123  // Configuration file is required.
124  if (config_file.empty()) {
125  cerr << "Configuration file not specified." << endl;
126  usage();
127  }
128 
129  // This is the DHCPv4 server
130  CfgMgr::instance().setFamily(AF_INET);
131 
132  if (check_mode) {
133  try {
134 
135  // We need to initialize logging, in case any error messages are to be printed.
136  // This is just a test, so we don't care about lockfile.
137  setenv("KEA_LOCKFILE_DIR", "none", 0);
138  Daemon::setDefaultLoggerName(DHCP4_ROOT_LOGGER_NAME);
139  Daemon::loggerInit(DHCP4_ROOT_LOGGER_NAME, verbose_mode);
140 
141  // Check the syntax first.
142  Parser4Context parser;
143  ConstElementPtr json;
144  json = parser.parseFile(config_file, Parser4Context::PARSER_DHCP4);
145  if (!json) {
146  cerr << "No configuration found" << endl;
147  return (EXIT_FAILURE);
148  }
149  if (verbose_mode) {
150  cerr << "Syntax check OK" << endl;
151  }
152 
153  // Check the logic next.
154  ConstElementPtr dhcp4 = json->get("Dhcp4");
155  if (!dhcp4) {
156  cerr << "Missing mandatory Dhcp4 element" << endl;
157  return (EXIT_FAILURE);
158  }
159  ControlledDhcpv4Srv server(0);
160  ConstElementPtr answer;
161 
162  // Now we pass the Dhcp4 configuration to the server, but
163  // tell it to check the configuration only (check_only = true)
164  answer = configureDhcp4Server(server, dhcp4, true);
165 
166  int status_code = 0;
167  answer = isc::config::parseAnswer(status_code, answer);
168  if (status_code == 0) {
169  return (EXIT_SUCCESS);
170  } else {
171  cerr << "Error encountered: " << answer->stringValue() << endl;
172  return (EXIT_FAILURE);
173  }
174  } catch (const std::exception& ex) {
175  cerr << "Syntax check failed with: " << ex.what() << endl;
176  }
177  return (EXIT_FAILURE);
178  }
179 
180  int ret = EXIT_SUCCESS;
181  try {
182  // It is important that we set a default logger name because this name
183  // will be used when the user doesn't provide the logging configuration
184  // in the Kea configuration file.
185  Daemon::setDefaultLoggerName(DHCP4_ROOT_LOGGER_NAME);
186 
187  // Initialize logging. If verbose, we'll use maximum verbosity.
188  Daemon::loggerInit(DHCP4_ROOT_LOGGER_NAME, verbose_mode);
189  LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_START_INFO)
190  .arg(getpid()).arg(port_number).arg(verbose_mode ? "yes" : "no");
191 
192  LOG_INFO(dhcp4_logger, DHCP4_STARTING).arg(VERSION);
193 
194  // Create the server instance.
195  ControlledDhcpv4Srv server(port_number);
196 
197  // Remember verbose-mode
198  server.setVerbose(verbose_mode);
199 
200  // Create our PID file.
201  server.setProcName(DHCP4_NAME);
202  server.setConfigFile(config_file);
203  server.createPIDFile();
204 
205  try {
206  // Initialize the server.
207  server.init(config_file);
208  } catch (const std::exception& ex) {
209 
210  try {
211  // Let's log out what went wrong.
212  isc::log::LoggerManager log_manager;
213  log_manager.process();
214  LOG_ERROR(dhcp4_logger, DHCP4_INIT_FAIL).arg(ex.what());
215  } catch (...) {
216  // The exception thrown during the initialization could
217  // originate from logger subsystem. Therefore LOG_ERROR()
218  // may fail as well.
219  cerr << "Failed to initialize server: " << ex.what() << endl;
220  }
221 
222  return (EXIT_FAILURE);
223  }
224 
225  // Tell the admin we are ready to process packets
226  LOG_INFO(dhcp4_logger, DHCP4_STARTED).arg(VERSION);
227 
228  // And run the main loop of the server.
229  server.run();
230 
231  LOG_INFO(dhcp4_logger, DHCP4_SHUTDOWN);
232 
233  } catch (const isc::process::DaemonPIDExists& ex) {
234  // First, we print the error on stderr (that should always work)
235  cerr << DHCP4_NAME << " already running? " << ex.what()
236  << endl;
237 
238  // Let's also try to log it using logging system, but we're not
239  // sure if it's usable (the exception may have been thrown from
240  // the logger subsystem)
241  try {
242  LOG_FATAL(dhcp4_logger, DHCP4_ALREADY_RUNNING)
243  .arg(DHCP4_NAME).arg(ex.what());
244  } catch (...) {
245  // Already logged so ignore
246  }
247  ret = EXIT_FAILURE;
248  } catch (const std::exception& ex) {
249  // First, we print the error on stderr (that should always work)
250  cerr << DHCP4_NAME << ": Fatal error during start up: " << ex.what()
251  << endl;
252 
253  // Let's also try to log it using logging system, but we're not
254  // sure if it's usable (the exception may have been thrown from
255  // the logger subsystem)
256  try {
257  LOG_FATAL(dhcp4_logger, DHCP4_SERVER_FAILED).arg(ex.what());
258  } catch (...) {
259  // Already logged so ignore
260  }
261  ret = EXIT_FAILURE;
262  }
263 
264  return (ret);
265 }
void init(const std::string &config_file)
Initializes the server.
isc::data::ElementPtr parseFile(const std::string &filename, ParserType parser_type)
Run the parser on the file specified.
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition: macros.h:20
Evaluation context, an interface to the expression evaluation.
void process(T start, T finish)
Process Specifications.
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition: macros.h:32
const int DBG_DHCP4_START
Debug level used to log information during server startup.
Definition: dhcp4_log.h:24
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
isc::data::ConstElementPtr configureDhcp4Server(Dhcpv4Srv &server, isc::data::ConstElementPtr config_set, bool check_only)
Configure DHCPv4 server (Dhcpv4Srv) with a set of configuration values.
isc::log::Logger dhcp4_logger(DHCP4_APP_LOGGER_NAME)
Base logger for DHCPv4 server.
Definition: dhcp4_log.h:90
int main(int argc, char *argv[])
Definition: dhcp4/main.cc:61
void setProcName(const std::string &proc_name)
Sets the process name.
Definition: daemon.cc:135
bool run()
Main server processing loop.
Definition: dhcp4_srv.cc:731
void setConfigFile(const std::string &config_file)
Sets the configuration file name.
Definition: daemon.cc:110
boost::shared_ptr< const Element > ConstElementPtr
Definition: data.h:23
static void setVerbose(const bool verbose)
Sets or clears verbose mode.
Definition: daemon.cc:79
ConstElementPtr parseAnswer(int &rcode, const ConstElementPtr &msg)
Logging initialization functions.
This file contains several functions and constants that are used for handling commands and responses ...
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition: macros.h:14
void usage()
Print Usage.
Controlled version of the DHCPv4 server.
std::string getConfigReport()
Definition: cfgrpt.cc:20
#define LOG_FATAL(LOGGER, MESSAGE)
Macro to conveniently test fatal output and log it.
Definition: macros.h:38
Exception thrown when a the PID file points to a live PID.
Definition: daemon.h:21
void createPIDFile(int pid=0)
Creates the PID file.
Definition: daemon.cc:203
Contains declarations for loggers used by the DHCPv4 server component.
const char * DHCP4_ROOT_LOGGER_NAME
Defines the name of the root level (default) logger.
Definition: dhcp4_log.cc:26