Kea  1.9.9-git
ctrl_dhcp4_srv.cc
Go to the documentation of this file.
1 // Copyright (C) 2014-2021 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 
10 #include <cc/data.h>
11 #include <cfgrpt/config_report.h>
12 #include <config/command_mgr.h>
13 #include <dhcp/libdhcp++.h>
14 #include <dhcp4/ctrl_dhcp4_srv.h>
15 #include <dhcp4/dhcp4_log.h>
16 #include <dhcp4/dhcp4to6_ipc.h>
18 #include <dhcp4/parser_context.h>
19 #include <dhcpsrv/cfg_db_access.h>
21 #include <dhcpsrv/cfgmgr.h>
22 #include <dhcpsrv/db_type.h>
23 #include <dhcpsrv/host_mgr.h>
25 #include <hooks/hooks.h>
26 #include <hooks/hooks_manager.h>
27 #include <stats/stats_mgr.h>
29 
30 #include <signal.h>
31 
32 #include <sstream>
33 
34 using namespace isc::asiolink;
35 using namespace isc::config;
36 using namespace isc::data;
37 using namespace isc::db;
38 using namespace isc::dhcp;
39 using namespace isc::hooks;
40 using namespace isc::stats;
41 using namespace isc::util;
42 using namespace std;
43 namespace ph = std::placeholders;
44 
45 namespace {
46 
48 struct CtrlDhcp4Hooks {
49  int hooks_index_dhcp4_srv_configured_;
50 
52  CtrlDhcp4Hooks() {
53  hooks_index_dhcp4_srv_configured_ = HooksManager::registerHook("dhcp4_srv_configured");
54  }
55 
56 };
57 
58 // Declare a Hooks object. As this is outside any function or method, it
59 // will be instantiated (and the constructor run) when the module is loaded.
60 // As a result, the hook indexes will be defined before any method in this
61 // module is called.
62 CtrlDhcp4Hooks Hooks;
63 
73 void signalHandler(int signo) {
74  // SIGHUP signals a request to reconfigure the server.
75  if (signo == SIGHUP) {
76  ControlledDhcpv4Srv::processCommand("config-reload",
77  ConstElementPtr());
78  } else if ((signo == SIGTERM) || (signo == SIGINT)) {
79  ControlledDhcpv4Srv::processCommand("shutdown",
80  ConstElementPtr());
81  }
82 }
83 
84 }
85 
86 namespace isc {
87 namespace dhcp {
88 
89 ControlledDhcpv4Srv* ControlledDhcpv4Srv::server_ = NULL;
90 
91 void
92 ControlledDhcpv4Srv::init(const std::string& file_name) {
93  // Keep the call timestamp.
94  start_ = boost::posix_time::second_clock::universal_time();
95 
96  // Configure the server using JSON file.
97  ConstElementPtr result = loadConfigFile(file_name);
98 
99  int rcode;
100  ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
101  if (rcode != CONTROL_RESULT_SUCCESS) {
102  string reason = comment ? comment->stringValue() :
103  "no details available";
104  isc_throw(isc::BadValue, reason);
105  }
106 
107  // We don't need to call openActiveSockets() or startD2() as these
108  // methods are called in processConfig() which is called by
109  // processCommand("config-set", ...)
110 
111  // Set signal handlers. When the SIGHUP is received by the process
112  // the server reconfiguration will be triggered. When SIGTERM or
113  // SIGINT will be received, the server will start shutting down.
114  signal_set_.reset(new IOSignalSet(getIOService(), signalHandler));
115 
116  signal_set_->add(SIGINT);
117  signal_set_->add(SIGHUP);
118  signal_set_->add(SIGTERM);
119 }
120 
121 void ControlledDhcpv4Srv::cleanup() {
122  // Nothing to do here. No need to disconnect from anything.
123 }
124 
126 ControlledDhcpv4Srv::loadConfigFile(const std::string& file_name) {
127  // This is a configuration backend implementation that reads the
128  // configuration from a JSON file.
129 
132 
133  // Basic sanity check: file name must not be empty.
134  try {
135  if (file_name.empty()) {
136  // Basic sanity check: file name must not be empty.
137  isc_throw(isc::BadValue, "JSON configuration file not specified."
138  " Please use -c command line option.");
139  }
140 
141  // Read contents of the file and parse it as JSON
142  Parser4Context parser;
143  json = parser.parseFile(file_name, Parser4Context::PARSER_DHCP4);
144  if (!json) {
145  isc_throw(isc::BadValue, "no configuration found");
146  }
147 
148  // Let's do sanity check before we call json->get() which
149  // works only for map.
150  if (json->getType() != isc::data::Element::map) {
151  isc_throw(isc::BadValue, "Configuration file is expected to be "
152  "a map, i.e., start with { and end with } and contain "
153  "at least an entry called 'Dhcp4' that itself is a map. "
154  << file_name
155  << " is a valid JSON, but its top element is not a map."
156  " Did you forget to add { } around your configuration?");
157  }
158 
159  // Use parsed JSON structures to configure the server
160  result = ControlledDhcpv4Srv::processCommand("config-set", json);
161  if (!result) {
162  // Undetermined status of the configuration. This should never
163  // happen, but as the configureDhcp4Server returns a pointer, it is
164  // theoretically possible that it will return NULL.
165  isc_throw(isc::BadValue, "undefined result of "
166  "processCommand(\"config-set\", json)");
167  }
168 
169  // Now check is the returned result is successful (rcode=0) or not
170  // (see @ref isc::config::parseAnswer).
171  int rcode;
172  ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
173  if (rcode != CONTROL_RESULT_SUCCESS) {
174  string reason = comment ? comment->stringValue() :
175  "no details available";
176  isc_throw(isc::BadValue, reason);
177  }
178  } catch (const std::exception& ex) {
179  // If configuration failed at any stage, we drop the staging
180  // configuration and continue to use the previous one.
181  CfgMgr::instance().rollback();
182 
184  .arg(file_name).arg(ex.what());
185  isc_throw(isc::BadValue, "configuration error using file '"
186  << file_name << "': " << ex.what());
187  }
188 
190  .arg(MultiThreadingMgr::instance().getMode() ? "yes" : "no")
191  .arg(MultiThreadingMgr::instance().getThreadPoolSize())
192  .arg(MultiThreadingMgr::instance().getPacketQueueSize());
193 
194  return (result);
195 }
196 
198 ControlledDhcpv4Srv::commandShutdownHandler(const string&, ConstElementPtr args) {
199  if (!ControlledDhcpv4Srv::getInstance()) {
201  return(createAnswer(CONTROL_RESULT_ERROR, "Shutdown failure."));
202  }
203 
204  int exit_value = 0;
205  if (args) {
206  // @todo Should we go ahead and shutdown even if the args are invalid?
207  if (args->getType() != Element::map) {
208  return (createAnswer(CONTROL_RESULT_ERROR, "Argument must be a map"));
209  }
210 
211  ConstElementPtr param = args->get("exit-value");
212  if (param) {
213  if (param->getType() != Element::integer) {
215  "parameter 'exit-value' is not an integer"));
216  }
217 
218  exit_value = param->intValue();
219  }
220  }
221 
222  ControlledDhcpv4Srv::getInstance()->shutdownServer(exit_value);
223  return (createAnswer(CONTROL_RESULT_SUCCESS, "Shutting down."));
224 }
225 
227 ControlledDhcpv4Srv::commandLibReloadHandler(const string&, ConstElementPtr) {
228  // stop thread pool (if running)
230 
231  // Clear the packet queue.
232  MultiThreadingMgr::instance().getThreadPool().reset();
233 
234  try {
236  HookLibsCollection loaded = HooksManager::getLibraryInfo();
237  HooksManager::prepareUnloadLibraries();
238  static_cast<void>(HooksManager::unloadLibraries());
239  bool status = HooksManager::loadLibraries(loaded);
240  if (!status) {
241  isc_throw(Unexpected, "Failed to reload hooks libraries.");
242  }
243  } catch (const std::exception& ex) {
245  ConstElementPtr answer = isc::config::createAnswer(1, ex.what());
246  return (answer);
247  }
249  "Hooks libraries successfully reloaded.");
250  return (answer);
251 }
252 
254 ControlledDhcpv4Srv::commandConfigReloadHandler(const string&,
255  ConstElementPtr /*args*/) {
256  // Get configuration file name.
257  std::string file = ControlledDhcpv4Srv::getInstance()->getConfigFile();
258  try {
260  return (loadConfigFile(file));
261  } catch (const std::exception& ex) {
262  // Log the unsuccessful reconfiguration. The reason for failure
263  // should be already logged. Don't rethrow an exception so as
264  // the server keeps working.
266  .arg(file);
268  "Config reload failed: " + string(ex.what())));
269  }
270 }
271 
273 ControlledDhcpv4Srv::commandConfigGetHandler(const string&,
274  ConstElementPtr /*args*/) {
275  ConstElementPtr config = CfgMgr::instance().getCurrentCfg()->toElement();
276 
277  return (createAnswer(0, config));
278 }
279 
281 ControlledDhcpv4Srv::commandConfigWriteHandler(const string&,
282  ConstElementPtr args) {
283  string filename;
284 
285  if (args) {
286  if (args->getType() != Element::map) {
287  return (createAnswer(CONTROL_RESULT_ERROR, "Argument must be a map"));
288  }
289  ConstElementPtr filename_param = args->get("filename");
290  if (filename_param) {
291  if (filename_param->getType() != Element::string) {
293  "passed parameter 'filename' is not a string"));
294  }
295  filename = filename_param->stringValue();
296  }
297  }
298 
299  if (filename.empty()) {
300  // filename parameter was not specified, so let's use whatever we remember
301  // from the command-line
302  filename = getConfigFile();
303  }
304 
305  if (filename.empty()) {
306  return (createAnswer(CONTROL_RESULT_ERROR, "Unable to determine filename."
307  "Please specify filename explicitly."));
308  }
309 
310  // Ok, it's time to write the file.
311  size_t size = 0;
312  try {
313  ConstElementPtr cfg = CfgMgr::instance().getCurrentCfg()->toElement();
314  size = writeConfigFile(filename, cfg);
315  } catch (const isc::Exception& ex) {
316  return (createAnswer(CONTROL_RESULT_ERROR, string("Error during write-config:")
317  + ex.what()));
318  }
319  if (size == 0) {
320  return (createAnswer(CONTROL_RESULT_ERROR, "Error writing configuration to "
321  + filename));
322  }
323 
324  // Ok, it's time to return the successful response.
325  ElementPtr params = Element::createMap();
326  params->set("size", Element::create(static_cast<long long>(size)));
327  params->set("filename", Element::create(filename));
328 
329  return (createAnswer(CONTROL_RESULT_SUCCESS, "Configuration written to "
330  + filename + " successful", params));
331 }
332 
334 ControlledDhcpv4Srv::commandConfigSetHandler(const string&,
335  ConstElementPtr args) {
336  const int status_code = CONTROL_RESULT_ERROR;
337  ConstElementPtr dhcp4;
338  string message;
339 
340  // Command arguments are expected to be:
341  // { "Dhcp4": { ... } }
342  if (!args) {
343  message = "Missing mandatory 'arguments' parameter.";
344  } else {
345  dhcp4 = args->get("Dhcp4");
346  if (!dhcp4) {
347  message = "Missing mandatory 'Dhcp4' parameter.";
348  } else if (dhcp4->getType() != Element::map) {
349  message = "'Dhcp4' parameter expected to be a map.";
350  }
351  }
352 
353  // Check unsupported objects.
354  if (message.empty()) {
355  for (auto obj : args->mapValue()) {
356  const string& obj_name = obj.first;
357  if (obj_name != "Dhcp4") {
359  .arg(obj_name);
360  if (message.empty()) {
361  message = "Unsupported '" + obj_name + "' parameter";
362  } else {
363  message += " (and '" + obj_name + "')";
364  }
365  }
366  }
367  if (!message.empty()) {
368  message += ".";
369  }
370  }
371 
372  if (!message.empty()) {
373  // Something is amiss with arguments, return a failure response.
374  ConstElementPtr result = isc::config::createAnswer(status_code,
375  message);
376  return (result);
377  }
378 
379  // stop thread pool (if running)
381 
382  // disable multi-threading (it will be applied by new configuration)
383  // this must be done in order to properly handle MT to ST transition
384  // when 'multi-threading' structure is missing from new config
385  MultiThreadingMgr::instance().apply(false, 0, 0);
386 
387  // We are starting the configuration process so we should remove any
388  // staging configuration that has been created during previous
389  // configuration attempts.
390  CfgMgr::instance().rollback();
391 
392  // Parse the logger configuration explicitly into the staging config.
393  // Note this does not alter the current loggers, they remain in
394  // effect until we apply the logging config below. If no logging
395  // is supplied logging will revert to default logging.
396  Daemon::configureLogger(dhcp4, CfgMgr::instance().getStagingCfg());
397 
398  // Let's apply the new logging. We do it early, so we'll be able to print
399  // out what exactly is wrong with the new config in case of problems.
400  CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
401 
402  // Now we configure the server proper.
403  ConstElementPtr result = processConfig(dhcp4);
404 
405  // If the configuration parsed successfully, apply the new logger
406  // configuration and the commit the new configuration. We apply
407  // the logging first in case there's a configuration failure.
408  int rcode = 0;
409  isc::config::parseAnswer(rcode, result);
410  if (rcode == CONTROL_RESULT_SUCCESS) {
411  CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
412 
413  // Use new configuration.
414  CfgMgr::instance().commit();
415  } else {
416  // Ok, we applied the logging from the upcoming configuration, but
417  // there were problems with the config. As such, we need to back off
418  // and revert to the previous logging configuration.
419  CfgMgr::instance().getCurrentCfg()->applyLoggingCfg();
420 
421  if (CfgMgr::instance().getCurrentCfg()->getSequence() != 0) {
422  // Not initial configuration so someone can believe we reverted
423  // to the previous configuration. It is not the case so be clear
424  // about this.
426  }
427  }
428 
429  return (result);
430 }
431 
433 ControlledDhcpv4Srv::commandConfigTestHandler(const string&,
434  ConstElementPtr args) {
435  const int status_code = CONTROL_RESULT_ERROR; // 1 indicates an error
436  ConstElementPtr dhcp4;
437  string message;
438 
439  // Command arguments are expected to be:
440  // { "Dhcp4": { ... } }
441  if (!args) {
442  message = "Missing mandatory 'arguments' parameter.";
443  } else {
444  dhcp4 = args->get("Dhcp4");
445  if (!dhcp4) {
446  message = "Missing mandatory 'Dhcp4' parameter.";
447  } else if (dhcp4->getType() != Element::map) {
448  message = "'Dhcp4' parameter expected to be a map.";
449  }
450  }
451 
452  // Check unsupported objects.
453  if (message.empty()) {
454  for (auto obj : args->mapValue()) {
455  const string& obj_name = obj.first;
456  if (obj_name != "Dhcp4") {
458  .arg(obj_name);
459  if (message.empty()) {
460  message = "Unsupported '" + obj_name + "' parameter";
461  } else {
462  message += " (and '" + obj_name + "')";
463  }
464  }
465  }
466  if (!message.empty()) {
467  message += ".";
468  }
469  }
470 
471  if (!message.empty()) {
472  // Something is amiss with arguments, return a failure response.
473  ConstElementPtr result = isc::config::createAnswer(status_code,
474  message);
475  return (result);
476  }
477 
478  // stop thread pool (if running)
480 
481  // We are starting the configuration process so we should remove any
482  // staging configuration that has been created during previous
483  // configuration attempts.
484  CfgMgr::instance().rollback();
485 
486  // Now we check the server proper.
487  return (checkConfig(dhcp4));
488 }
489 
491 ControlledDhcpv4Srv::commandDhcpDisableHandler(const std::string&,
492  ConstElementPtr args) {
493  std::ostringstream message;
494  int64_t max_period = 0;
495  std::string origin;
496 
497  // If the args map does not contain 'origin' parameter, the default type
498  // will be used (user command).
499  NetworkState::Origin type = NetworkState::Origin::USER_COMMAND;
500 
501  // Parse arguments to see if the 'max-period' or 'origin' parameters have
502  // been specified.
503  if (args) {
504  // Arguments must be a map.
505  if (args->getType() != Element::map) {
506  message << "arguments for the 'dhcp-disable' command must be a map";
507 
508  } else {
509  ConstElementPtr max_period_element = args->get("max-period");
510  // max-period is optional.
511  if (max_period_element) {
512  // It must be an integer, if specified.
513  if (max_period_element->getType() != Element::integer) {
514  message << "'max-period' argument must be a number";
515 
516  } else {
517  // It must be positive integer.
518  max_period = max_period_element->intValue();
519  if (max_period <= 0) {
520  message << "'max-period' must be positive integer";
521  }
522  }
523  }
524  ConstElementPtr origin_element = args->get("origin");
525  // The 'origin' parameter is optional.
526  if (origin_element) {
527  // It must be a string, if specified.
528  if (origin_element->getType() != Element::string) {
529  message << "'origin' argument must be a string";
530 
531  } else {
532  origin = origin_element->stringValue();
533  if (origin == "ha-partner") {
534  type = NetworkState::Origin::HA_COMMAND;
535  } else if (origin != "user") {
536  if (origin.empty()) {
537  origin = "(empty string)";
538  }
539  message << "invalid value used for 'origin' parameter: "
540  << origin;
541  }
542  }
543  }
544  }
545  }
546 
547  // No error occurred, so let's disable the service.
548  if (message.tellp() == 0) {
549  message << "DHCPv4 service disabled";
550  if (max_period > 0) {
551  message << " for " << max_period << " seconds";
552 
553  // The user specified that the DHCP service should resume not
554  // later than in max-period seconds. If the 'dhcp-enable' command
555  // is not sent, the DHCP service will resume automatically.
556  network_state_->delayedEnableAll(static_cast<unsigned>(max_period),
557  type);
558  }
559  network_state_->disableService(type);
560 
561  // Success.
562  return (config::createAnswer(CONTROL_RESULT_SUCCESS, message.str()));
563  }
564 
565  // Failure.
566  return (config::createAnswer(CONTROL_RESULT_ERROR, message.str()));
567 }
568 
570 ControlledDhcpv4Srv::commandDhcpEnableHandler(const std::string&,
571  ConstElementPtr args) {
572  std::ostringstream message;
573  std::string origin;
574 
575  // If the args map does not contain 'origin' parameter, the default type
576  // will be used (user command).
577  NetworkState::Origin type = NetworkState::Origin::USER_COMMAND;
578 
579  // Parse arguments to see if the 'origin' parameter has been specified.
580  if (args) {
581  // Arguments must be a map.
582  if (args->getType() != Element::map) {
583  message << "arguments for the 'dhcp-enable' command must be a map";
584 
585  } else {
586  ConstElementPtr origin_element = args->get("origin");
587  // The 'origin' parameter is optional.
588  if (origin_element) {
589  // It must be a string, if specified.
590  if (origin_element->getType() != Element::string) {
591  message << "'origin' argument must be a string";
592 
593  } else {
594  origin = origin_element->stringValue();
595  if (origin == "ha-partner") {
596  type = NetworkState::Origin::HA_COMMAND;
597  } else if (origin != "user") {
598  if (origin.empty()) {
599  origin = "(empty string)";
600  }
601  message << "invalid value used for 'origin' parameter: "
602  << origin;
603  }
604  }
605  }
606  }
607  }
608 
609  // No error occurred, so let's enable the service.
610  if (message.tellp() == 0) {
611  network_state_->enableService(type);
612 
613  // Success.
615  "DHCP service successfully enabled"));
616  }
617 
618  // Failure.
619  return (config::createAnswer(CONTROL_RESULT_ERROR, message.str()));
620 }
621 
623 ControlledDhcpv4Srv::commandVersionGetHandler(const string&, ConstElementPtr) {
624  ElementPtr extended = Element::create(Dhcpv4Srv::getVersion(true));
625  ElementPtr arguments = Element::createMap();
626  arguments->set("extended", extended);
628  Dhcpv4Srv::getVersion(false),
629  arguments);
630  return (answer);
631 }
632 
634 ControlledDhcpv4Srv::commandBuildReportHandler(const string&,
635  ConstElementPtr) {
636  ConstElementPtr answer =
638  return (answer);
639 }
640 
642 ControlledDhcpv4Srv::commandLeasesReclaimHandler(const string&,
643  ConstElementPtr args) {
644  int status_code = CONTROL_RESULT_ERROR;
645  string message;
646 
647  // args must be { "remove": <bool> }
648  if (!args) {
649  message = "Missing mandatory 'remove' parameter.";
650  } else {
651  ConstElementPtr remove_name = args->get("remove");
652  if (!remove_name) {
653  message = "Missing mandatory 'remove' parameter.";
654  } else if (remove_name->getType() != Element::boolean) {
655  message = "'remove' parameter expected to be a boolean.";
656  } else {
657  bool remove_lease = remove_name->boolValue();
658  server_->alloc_engine_->reclaimExpiredLeases4(0, 0, remove_lease);
659  status_code = 0;
660  message = "Reclamation of expired leases is complete.";
661  }
662  }
663  ConstElementPtr answer = isc::config::createAnswer(status_code, message);
664  return (answer);
665 }
666 
668 ControlledDhcpv4Srv::commandServerTagGetHandler(const std::string&,
669  ConstElementPtr) {
670  const std::string& tag =
671  CfgMgr::instance().getCurrentCfg()->getServerTag();
672  ElementPtr response = Element::createMap();
673  response->set("server-tag", Element::create(tag));
674 
675  return (createAnswer(CONTROL_RESULT_SUCCESS, response));
676 }
677 
679 ControlledDhcpv4Srv::commandConfigBackendPullHandler(const std::string&,
680  ConstElementPtr) {
681  auto ctl_info = CfgMgr::instance().getCurrentCfg()->getConfigControlInfo();
682  if (!ctl_info) {
683  return (createAnswer(CONTROL_RESULT_EMPTY, "No config backend."));
684  }
685 
686  // stop thread pool (if running)
688 
689  // Reschedule the periodic CB fetch.
690  if (TimerMgr::instance()->isTimerRegistered("Dhcp4CBFetchTimer")) {
691  TimerMgr::instance()->cancel("Dhcp4CBFetchTimer");
692  TimerMgr::instance()->setup("Dhcp4CBFetchTimer");
693  }
694 
695  // Code from cbFetchUpdates.
696  // The configuration to use is the current one because this is called
697  // after the configuration manager commit.
698  try {
699  auto srv_cfg = CfgMgr::instance().getCurrentCfg();
700  auto mode = CBControlDHCPv4::FetchMode::FETCH_UPDATE;
701  server_->getCBControl()->databaseConfigFetch(srv_cfg, mode);
702  } catch (const std::exception& ex) {
704  .arg(ex.what());
706  "On demand configuration update failed: " +
707  string(ex.what())));
708  }
710  "On demand configuration update successful."));
711 }
712 
714 ControlledDhcpv4Srv::commandStatusGetHandler(const string&,
715  ConstElementPtr /*args*/) {
716  ElementPtr status = Element::createMap();
717  status->set("pid", Element::create(static_cast<int>(getpid())));
718 
719  auto now = boost::posix_time::second_clock::universal_time();
720  // Sanity check: start_ is always initialized.
721  if (!start_.is_not_a_date_time()) {
722  auto uptime = now - start_;
723  status->set("uptime", Element::create(uptime.total_seconds()));
724  }
725 
726  auto last_commit = CfgMgr::instance().getCurrentCfg()->getLastCommitTime();
727  if (!last_commit.is_not_a_date_time()) {
728  auto reload = now - last_commit;
729  status->set("reload", Element::create(reload.total_seconds()));
730  }
731 
732  auto& mt_mgr = MultiThreadingMgr::instance();
733  if (mt_mgr.getMode()) {
734  status->set("multi-threading-enabled", Element::create(true));
735  status->set("thread-pool-size", Element::create(static_cast<int32_t>(
736  MultiThreadingMgr::instance().getThreadPoolSize())));
737  status->set("packet-queue-size", Element::create(static_cast<int32_t>(
738  MultiThreadingMgr::instance().getPacketQueueSize())));
739  ElementPtr queue_stats = Element::createList();
740  queue_stats->add(Element::create(mt_mgr.getThreadPool().getQueueStat(10)));
741  queue_stats->add(Element::create(mt_mgr.getThreadPool().getQueueStat(100)));
742  queue_stats->add(Element::create(mt_mgr.getThreadPool().getQueueStat(1000)));
743  status->set("packet-queue-statistics", queue_stats);
744 
745  } else {
746  status->set("multi-threading-enabled", Element::create(false));
747  }
748 
749  return (createAnswer(0, status));
750 }
751 
753 ControlledDhcpv4Srv::commandStatisticSetMaxSampleCountAllHandler(const string&,
754  ConstElementPtr args) {
755  StatsMgr& stats_mgr = StatsMgr::instance();
756  ConstElementPtr answer = stats_mgr.statisticSetMaxSampleCountAllHandler(args);
757  // Update the default parameter.
758  long max_samples = stats_mgr.getMaxSampleCountDefault();
759  CfgMgr::instance().getCurrentCfg()->addConfiguredGlobal(
760  "statistic-default-sample-count", Element::create(max_samples));
761  return (answer);
762 }
763 
765 ControlledDhcpv4Srv::commandStatisticSetMaxSampleAgeAllHandler(const string&,
766  ConstElementPtr args) {
767  StatsMgr& stats_mgr = StatsMgr::instance();
768  ConstElementPtr answer = stats_mgr.statisticSetMaxSampleAgeAllHandler(args);
769  // Update the default parameter.
770  auto duration = stats_mgr.getMaxSampleAgeDefault();
771  long max_age = toSeconds(duration);
772  CfgMgr::instance().getCurrentCfg()->addConfiguredGlobal(
773  "statistic-default-sample-age", Element::create(max_age));
774  return (answer);
775 }
776 
778 ControlledDhcpv4Srv::processCommand(const string& command,
779  ConstElementPtr args) {
780  string txt = args ? args->str() : "(none)";
781 
783  .arg(command).arg(txt);
784 
785  ControlledDhcpv4Srv* srv = ControlledDhcpv4Srv::getInstance();
786 
787  if (!srv) {
789  "Server object not initialized, so can't process command '" +
790  command + "', arguments: '" + txt + "'.");
791  return (no_srv);
792  }
793 
794  try {
795  if (command == "shutdown") {
796  return (srv->commandShutdownHandler(command, args));
797 
798  } else if (command == "libreload") {
799  return (srv->commandLibReloadHandler(command, args));
800 
801  } else if (command == "config-reload") {
802  return (srv->commandConfigReloadHandler(command, args));
803 
804  } else if (command == "config-set") {
805  return (srv->commandConfigSetHandler(command, args));
806 
807  } else if (command == "config-get") {
808  return (srv->commandConfigGetHandler(command, args));
809 
810  } else if (command == "config-test") {
811  return (srv->commandConfigTestHandler(command, args));
812 
813  } else if (command == "dhcp-disable") {
814  return (srv->commandDhcpDisableHandler(command, args));
815 
816  } else if (command == "dhcp-enable") {
817  return (srv->commandDhcpEnableHandler(command, args));
818 
819  } else if (command == "version-get") {
820  return (srv->commandVersionGetHandler(command, args));
821 
822  } else if (command == "build-report") {
823  return (srv->commandBuildReportHandler(command, args));
824 
825  } else if (command == "leases-reclaim") {
826  return (srv->commandLeasesReclaimHandler(command, args));
827 
828  } else if (command == "config-write") {
829  return (srv->commandConfigWriteHandler(command, args));
830 
831  } else if (command == "server-tag-get") {
832  return (srv->commandServerTagGetHandler(command, args));
833 
834  } else if (command == "config-backend-pull") {
835  return (srv->commandConfigBackendPullHandler(command, args));
836 
837  } else if (command == "status-get") {
838  return (srv->commandStatusGetHandler(command, args));
839  }
840 
841  return (isc::config::createAnswer(1, "Unrecognized command:"
842  + command));
843 
844  } catch (const isc::Exception& ex) {
845  return (isc::config::createAnswer(1, "Error while processing command '"
846  + command + "':" + ex.what() +
847  ", params: '" + txt + "'"));
848  }
849 }
850 
852 ControlledDhcpv4Srv::processConfig(isc::data::ConstElementPtr config) {
853  ControlledDhcpv4Srv* srv = ControlledDhcpv4Srv::getInstance();
854 
855  // Single stream instance used in all error clauses
856  std::ostringstream err;
857 
858  if (!srv) {
859  err << "Server object not initialized, can't process config.";
860  return (isc::config::createAnswer(1, err.str()));
861  }
862 
864  .arg(srv->redactConfig(config)->str());
865 
866  ConstElementPtr answer = configureDhcp4Server(*srv, config);
867 
868  // Check that configuration was successful. If not, do not reopen sockets
869  // and don't bother with DDNS stuff.
870  try {
871  int rcode = 0;
872  isc::config::parseAnswer(rcode, answer);
873  if (rcode != 0) {
874  return (answer);
875  }
876  } catch (const std::exception& ex) {
877  err << "Failed to process configuration:" << ex.what();
878  return (isc::config::createAnswer(1, err.str()));
879  }
880 
881  // Re-open lease and host database with new parameters.
882  try {
883  DatabaseConnection::db_lost_callback_ =
884  std::bind(&ControlledDhcpv4Srv::dbLostCallback, srv, ph::_1);
885 
886  DatabaseConnection::db_recovered_callback_ =
887  std::bind(&ControlledDhcpv4Srv::dbRecoveredCallback, srv, ph::_1);
888 
889  DatabaseConnection::db_failed_callback_ =
890  std::bind(&ControlledDhcpv4Srv::dbFailedCallback, srv, ph::_1);
891 
892  CfgDbAccessPtr cfg_db = CfgMgr::instance().getStagingCfg()->getCfgDbAccess();
893  cfg_db->setAppendedParameters("universe=4");
894  cfg_db->createManagers();
895  // Reset counters related to connections as all managers have been recreated.
896  srv->getNetworkState()->reset(NetworkState::Origin::DB_CONNECTION);
897  } catch (const std::exception& ex) {
898  err << "Unable to open database: " << ex.what();
899  return (isc::config::createAnswer(1, err.str()));
900  }
901 
902  // Server will start DDNS communications if its enabled.
903  try {
904  srv->startD2();
905  } catch (const std::exception& ex) {
906  err << "Error starting DHCP_DDNS client after server reconfiguration: "
907  << ex.what();
908  return (isc::config::createAnswer(1, err.str()));
909  }
910 
911  // Setup DHCPv4-over-DHCPv6 IPC
912  try {
913  Dhcp4to6Ipc::instance().open();
914  } catch (const std::exception& ex) {
915  std::ostringstream err;
916  err << "error starting DHCPv4-over-DHCPv6 IPC "
917  " after server reconfiguration: " << ex.what();
918  return (isc::config::createAnswer(1, err.str()));
919  }
920 
921  // Configure DHCP packet queueing
922  try {
924  qc = CfgMgr::instance().getStagingCfg()->getDHCPQueueControl();
925  if (IfaceMgr::instance().configureDHCPPacketQueue(AF_INET, qc)) {
927  .arg(IfaceMgr::instance().getPacketQueue4()->getInfoStr());
928  }
929 
930  } catch (const std::exception& ex) {
931  err << "Error setting packet queue controls after server reconfiguration: "
932  << ex.what();
933  return (isc::config::createAnswer(1, err.str()));
934  }
935 
936  // Configuration may change active interfaces. Therefore, we have to reopen
937  // sockets according to new configuration. It is possible that this
938  // operation will fail for some interfaces but the openSockets function
939  // guards against exceptions and invokes a callback function to
940  // log warnings. Since we allow that this fails for some interfaces there
941  // is no need to rollback configuration if socket fails to open on any
942  // of the interfaces.
943  CfgMgr::instance().getStagingCfg()->getCfgIface()->
944  openSockets(AF_INET, srv->getServerPort(),
945  getInstance()->useBroadcast());
946 
947  // Install the timers for handling leases reclamation.
948  try {
949  CfgMgr::instance().getStagingCfg()->getCfgExpiration()->
950  setupTimers(&ControlledDhcpv4Srv::reclaimExpiredLeases,
951  &ControlledDhcpv4Srv::deleteExpiredReclaimedLeases,
952  server_);
953 
954  } catch (const std::exception& ex) {
955  err << "unable to setup timers for periodically running the"
956  " reclamation of the expired leases: "
957  << ex.what() << ".";
958  return (isc::config::createAnswer(1, err.str()));
959  }
960 
961  // Setup config backend polling, if configured for it.
962  auto ctl_info = CfgMgr::instance().getStagingCfg()->getConfigControlInfo();
963  if (ctl_info) {
964  long fetch_time = static_cast<long>(ctl_info->getConfigFetchWaitTime());
965  // Only schedule the CB fetch timer if the fetch wait time is greater
966  // than 0.
967  if (fetch_time > 0) {
968  // When we run unit tests, we want to use milliseconds unit for the
969  // specified interval. Otherwise, we use seconds. Note that using
970  // milliseconds as a unit in unit tests prevents us from waiting 1
971  // second on more before the timer goes off. Instead, we wait one
972  // millisecond which significantly reduces the test time.
973  if (!server_->inTestMode()) {
974  fetch_time = 1000 * fetch_time;
975  }
976 
977  boost::shared_ptr<unsigned> failure_count(new unsigned(0));
978  TimerMgr::instance()->
979  registerTimer("Dhcp4CBFetchTimer",
980  std::bind(&ControlledDhcpv4Srv::cbFetchUpdates,
981  server_, CfgMgr::instance().getStagingCfg(),
982  failure_count),
983  fetch_time,
985  TimerMgr::instance()->setup("Dhcp4CBFetchTimer");
986  }
987  }
988 
989  // Finally, we can commit runtime option definitions in libdhcp++. This is
990  // exception free.
991  LibDHCP::commitRuntimeOptionDefs();
992 
993  // This hook point notifies hooks libraries that the configuration of the
994  // DHCPv4 server has completed. It provides the hook library with the pointer
995  // to the common IO service object, new server configuration in the JSON
996  // format and with the pointer to the configuration storage where the
997  // parsed configuration is stored.
998  if (HooksManager::calloutsPresent(Hooks.hooks_index_dhcp4_srv_configured_)) {
999  CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
1000 
1001  callout_handle->setArgument("io_context", srv->getIOService());
1002  callout_handle->setArgument("network_state", srv->getNetworkState());
1003  callout_handle->setArgument("json_config", config);
1004  callout_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
1005 
1006  HooksManager::callCallouts(Hooks.hooks_index_dhcp4_srv_configured_,
1007  *callout_handle);
1008 
1009  // Ignore status code as none of them would have an effect on further
1010  // operation.
1011  }
1012 
1013  // Apply multi threading settings.
1014  // @note These settings are applied/updated only if no errors occur while
1015  // applying the new configuration.
1016  // @todo This should be fixed.
1017  try {
1018  CfgMultiThreading::apply(CfgMgr::instance().getStagingCfg()->getDHCPMultiThreading());
1019  } catch (const std::exception& ex) {
1020  err << "Error applying multi threading settings: "
1021  << ex.what();
1022  return (isc::config::createAnswer(CONTROL_RESULT_ERROR, err.str()));
1023  }
1024 
1025  return (answer);
1026 }
1027 
1029 ControlledDhcpv4Srv::checkConfig(isc::data::ConstElementPtr config) {
1030 
1032  .arg(redactConfig(config)->str());
1033 
1034  ControlledDhcpv4Srv* srv = ControlledDhcpv4Srv::getInstance();
1035 
1036  // Single stream instance used in all error clauses
1037  std::ostringstream err;
1038 
1039  if (!srv) {
1040  err << "Server object not initialized, can't process config.";
1041  return (isc::config::createAnswer(1, err.str()));
1042  }
1043 
1044  return (configureDhcp4Server(*srv, config, true));
1045 }
1046 
1047 ControlledDhcpv4Srv::ControlledDhcpv4Srv(uint16_t server_port /*= DHCP4_SERVER_PORT*/,
1048  uint16_t client_port /*= 0*/)
1049  : Dhcpv4Srv(server_port, client_port), timer_mgr_(TimerMgr::instance()) {
1050  if (getInstance()) {
1052  "There is another Dhcpv4Srv instance already.");
1053  }
1054  server_ = this; // remember this instance for later use in handlers
1055 
1056  // TimerMgr uses IO service to run asynchronous timers.
1057  TimerMgr::instance()->setIOService(getIOService());
1058 
1059  // CommandMgr uses IO service to run asynchronous socket operations.
1060  CommandMgr::instance().setIOService(getIOService());
1061 
1062  // LeaseMgr uses IO service to run asynchronous timers.
1064 
1065  // HostMgr uses IO service to run asynchronous timers.
1067 
1068  // These are the commands always supported by the DHCPv4 server.
1069  // Please keep the list in alphabetic order.
1070  CommandMgr::instance().registerCommand("build-report",
1071  std::bind(&ControlledDhcpv4Srv::commandBuildReportHandler, this, ph::_1, ph::_2));
1072 
1073  CommandMgr::instance().registerCommand("config-backend-pull",
1074  std::bind(&ControlledDhcpv4Srv::commandConfigBackendPullHandler, this, ph::_1, ph::_2));
1075 
1076  CommandMgr::instance().registerCommand("config-get",
1077  std::bind(&ControlledDhcpv4Srv::commandConfigGetHandler, this, ph::_1, ph::_2));
1078 
1079  CommandMgr::instance().registerCommand("config-reload",
1080  std::bind(&ControlledDhcpv4Srv::commandConfigReloadHandler, this, ph::_1, ph::_2));
1081 
1082  CommandMgr::instance().registerCommand("config-set",
1083  std::bind(&ControlledDhcpv4Srv::commandConfigSetHandler, this, ph::_1, ph::_2));
1084 
1085  CommandMgr::instance().registerCommand("config-test",
1086  std::bind(&ControlledDhcpv4Srv::commandConfigTestHandler, this, ph::_1, ph::_2));
1087 
1088  CommandMgr::instance().registerCommand("config-write",
1089  std::bind(&ControlledDhcpv4Srv::commandConfigWriteHandler, this, ph::_1, ph::_2));
1090 
1091  CommandMgr::instance().registerCommand("dhcp-enable",
1092  std::bind(&ControlledDhcpv4Srv::commandDhcpEnableHandler, this, ph::_1, ph::_2));
1093 
1094  CommandMgr::instance().registerCommand("dhcp-disable",
1095  std::bind(&ControlledDhcpv4Srv::commandDhcpDisableHandler, this, ph::_1, ph::_2));
1096 
1097  CommandMgr::instance().registerCommand("libreload",
1098  std::bind(&ControlledDhcpv4Srv::commandLibReloadHandler, this, ph::_1, ph::_2));
1099 
1100  CommandMgr::instance().registerCommand("leases-reclaim",
1101  std::bind(&ControlledDhcpv4Srv::commandLeasesReclaimHandler, this, ph::_1, ph::_2));
1102 
1103  CommandMgr::instance().registerCommand("server-tag-get",
1104  std::bind(&ControlledDhcpv4Srv::commandServerTagGetHandler, this, ph::_1, ph::_2));
1105 
1106  CommandMgr::instance().registerCommand("shutdown",
1107  std::bind(&ControlledDhcpv4Srv::commandShutdownHandler, this, ph::_1, ph::_2));
1108 
1109  CommandMgr::instance().registerCommand("status-get",
1110  std::bind(&ControlledDhcpv4Srv::commandStatusGetHandler, this, ph::_1, ph::_2));
1111 
1112  CommandMgr::instance().registerCommand("version-get",
1113  std::bind(&ControlledDhcpv4Srv::commandVersionGetHandler, this, ph::_1, ph::_2));
1114 
1115  // Register statistic related commands
1116  CommandMgr::instance().registerCommand("statistic-get",
1117  std::bind(&StatsMgr::statisticGetHandler, ph::_1, ph::_2));
1118 
1119  CommandMgr::instance().registerCommand("statistic-reset",
1120  std::bind(&StatsMgr::statisticResetHandler, ph::_1, ph::_2));
1121 
1122  CommandMgr::instance().registerCommand("statistic-remove",
1123  std::bind(&StatsMgr::statisticRemoveHandler, ph::_1, ph::_2));
1124 
1125  CommandMgr::instance().registerCommand("statistic-get-all",
1126  std::bind(&StatsMgr::statisticGetAllHandler, ph::_1, ph::_2));
1127 
1128  CommandMgr::instance().registerCommand("statistic-reset-all",
1129  std::bind(&StatsMgr::statisticResetAllHandler, ph::_1, ph::_2));
1130 
1131  CommandMgr::instance().registerCommand("statistic-remove-all",
1132  std::bind(&StatsMgr::statisticRemoveAllHandler, ph::_1, ph::_2));
1133 
1134  CommandMgr::instance().registerCommand("statistic-sample-age-set",
1135  std::bind(&StatsMgr::statisticSetMaxSampleAgeHandler, ph::_1, ph::_2));
1136 
1137  CommandMgr::instance().registerCommand("statistic-sample-age-set-all",
1138  std::bind(&ControlledDhcpv4Srv::commandStatisticSetMaxSampleAgeAllHandler, this, ph::_1, ph::_2));
1139 
1140  CommandMgr::instance().registerCommand("statistic-sample-count-set",
1141  std::bind(&StatsMgr::statisticSetMaxSampleCountHandler, ph::_1, ph::_2));
1142 
1143  CommandMgr::instance().registerCommand("statistic-sample-count-set-all",
1144  std::bind(&ControlledDhcpv4Srv::commandStatisticSetMaxSampleCountAllHandler, this, ph::_1, ph::_2));
1145 }
1146 
1148  setExitValue(exit_value);
1149  getIOService()->stop(); // Stop ASIO transmissions
1150  shutdown(); // Initiate DHCPv4 shutdown procedure.
1151 }
1152 
1154  try {
1156  HostMgr::create();
1157  cleanup();
1158 
1159  // The closure captures either a shared pointer (memory leak)
1160  // or a raw pointer (pointing to a deleted object).
1164 
1165  timer_mgr_->unregisterTimers();
1166 
1167  // Close the command socket (if it exists).
1168  CommandMgr::instance().closeCommandSocket();
1169 
1170  // Deregister any registered commands (please keep in alphabetic order)
1171  CommandMgr::instance().deregisterCommand("build-report");
1172  CommandMgr::instance().deregisterCommand("config-backend-pull");
1173  CommandMgr::instance().deregisterCommand("config-get");
1174  CommandMgr::instance().deregisterCommand("config-reload");
1175  CommandMgr::instance().deregisterCommand("config-set");
1176  CommandMgr::instance().deregisterCommand("config-test");
1177  CommandMgr::instance().deregisterCommand("config-write");
1178  CommandMgr::instance().deregisterCommand("dhcp-disable");
1179  CommandMgr::instance().deregisterCommand("dhcp-enable");
1180  CommandMgr::instance().deregisterCommand("leases-reclaim");
1181  CommandMgr::instance().deregisterCommand("libreload");
1182  CommandMgr::instance().deregisterCommand("server-tag-get");
1183  CommandMgr::instance().deregisterCommand("shutdown");
1184  CommandMgr::instance().deregisterCommand("statistic-get");
1185  CommandMgr::instance().deregisterCommand("statistic-get-all");
1186  CommandMgr::instance().deregisterCommand("statistic-remove");
1187  CommandMgr::instance().deregisterCommand("statistic-remove-all");
1188  CommandMgr::instance().deregisterCommand("statistic-reset");
1189  CommandMgr::instance().deregisterCommand("statistic-reset-all");
1190  CommandMgr::instance().deregisterCommand("statistic-sample-age-set");
1191  CommandMgr::instance().deregisterCommand("statistic-sample-age-set-all");
1192  CommandMgr::instance().deregisterCommand("statistic-sample-count-set");
1193  CommandMgr::instance().deregisterCommand("statistic-sample-count-set-all");
1194  CommandMgr::instance().deregisterCommand("status-get");
1195  CommandMgr::instance().deregisterCommand("version-get");
1196 
1197  // LeaseMgr uses IO service to run asynchronous timers.
1199 
1200  // HostMgr uses IO service to run asynchronous timers.
1202  } catch (...) {
1203  // Don't want to throw exceptions from the destructor. The server
1204  // is shutting down anyway.
1205  ;
1206  }
1207 
1208  server_ = NULL; // forget this instance. There should be no callback anymore
1209  // at this stage anyway.
1210 }
1211 
1212 void
1213 ControlledDhcpv4Srv::reclaimExpiredLeases(const size_t max_leases,
1214  const uint16_t timeout,
1215  const bool remove_lease,
1216  const uint16_t max_unwarned_cycles) {
1217  try {
1218  server_->alloc_engine_->reclaimExpiredLeases4(max_leases, timeout,
1219  remove_lease,
1220  max_unwarned_cycles);
1221  } catch (const std::exception& ex) {
1223  .arg(ex.what());
1224  }
1225  // We're using the ONE_SHOT timer so there is a need to re-schedule it.
1227 }
1228 
1229 void
1230 ControlledDhcpv4Srv::deleteExpiredReclaimedLeases(const uint32_t secs) {
1231  server_->alloc_engine_->deleteExpiredReclaimedLeases4(secs);
1232  // We're using the ONE_SHOT timer so there is a need to re-schedule it.
1234 }
1235 
1236 bool
1237 ControlledDhcpv4Srv::dbLostCallback(ReconnectCtlPtr db_reconnect_ctl) {
1238  if (!db_reconnect_ctl) {
1239  // This should never happen
1241  return (false);
1242  }
1243 
1244  // Disable service until the connection is recovered.
1245  if (db_reconnect_ctl->retriesLeft() == db_reconnect_ctl->maxRetries() &&
1246  db_reconnect_ctl->alterServiceState()) {
1248  }
1249 
1251 
1252  // If reconnect isn't enabled log it, initiate a shutdown if needed and
1253  // return false.
1254  if (!db_reconnect_ctl->retriesLeft() ||
1255  !db_reconnect_ctl->retryInterval()) {
1257  .arg(db_reconnect_ctl->retriesLeft())
1258  .arg(db_reconnect_ctl->retryInterval());
1259  if (db_reconnect_ctl->exitOnFailure()) {
1260  shutdownServer(EXIT_FAILURE);
1261  }
1262  return (false);
1263  }
1264 
1265  return (true);
1266 }
1267 
1268 bool
1269 ControlledDhcpv4Srv::dbRecoveredCallback(ReconnectCtlPtr db_reconnect_ctl) {
1270  if (!db_reconnect_ctl) {
1271  // This should never happen
1273  return (false);
1274  }
1275 
1276  // Enable service after the connection is recovered.
1277  if (db_reconnect_ctl->alterServiceState()) {
1279  }
1280 
1282 
1283  db_reconnect_ctl->resetRetries();
1284 
1285  return (true);
1286 }
1287 
1288 bool
1289 ControlledDhcpv4Srv::dbFailedCallback(ReconnectCtlPtr db_reconnect_ctl) {
1290  if (!db_reconnect_ctl) {
1291  // This should never happen
1293  return (false);
1294  }
1295 
1297  .arg(db_reconnect_ctl->maxRetries());
1298 
1299  if (db_reconnect_ctl->exitOnFailure()) {
1300  shutdownServer(EXIT_FAILURE);
1301  }
1302 
1303  return (true);
1304 }
1305 
1306 void
1307 ControlledDhcpv4Srv::cbFetchUpdates(const SrvConfigPtr& srv_cfg,
1308  boost::shared_ptr<unsigned> failure_count) {
1309  // stop thread pool (if running)
1311 
1312  try {
1313  // Fetch any configuration backend updates since our last fetch.
1314  server_->getCBControl()->databaseConfigFetch(srv_cfg,
1315  CBControlDHCPv4::FetchMode::FETCH_UPDATE);
1316  (*failure_count) = 0;
1317 
1318  } catch (const std::exception& ex) {
1320  .arg(ex.what());
1321 
1322  // We allow at most 10 consecutive failures after which we stop
1323  // making further attempts to fetch the configuration updates.
1324  // Let's return without re-scheduling the timer.
1325  if (++(*failure_count) > 10) {
1328  return;
1329  }
1330  }
1331 
1332  // Reschedule the timer to fetch new updates or re-try if
1333  // the previous attempt resulted in an error.
1334  if (TimerMgr::instance()->isTimerRegistered("Dhcp4CBFetchTimer")) {
1335  TimerMgr::instance()->setup("Dhcp4CBFetchTimer");
1336  }
1337 }
1338 
1339 } // namespace dhcp
1340 } // namespace isc
DHCPv4 server service.
Definition: dhcp4_srv.h:241
RAII class creating a critical section.
const isc::log::MessageID DHCP4_RECLAIM_EXPIRED_LEASES_FAIL
#define LOG_WARN(LOGGER, MESSAGE)
Macro to conveniently test warn output and log it.
Definition: macros.h:26
const isc::log::MessageID DHCP4_DB_RECONNECT_LOST_CONNECTION
const isc::log::MessageID DHCP4_DYNAMIC_RECONFIGURATION_FAIL
static DbCallback db_lost_callback_
Optional callback function to invoke if an opened connection is lost.
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
ConstElementPtr createAnswer(const int status_code, const std::string &text, const ConstElementPtr &arg)
const int CONTROL_RESULT_SUCCESS
Status code indicating a successful operation.
static void setIOService(const isc::asiolink::IOServicePtr &io_service)
Sets IO service to be used by the Host Manager.
Definition: host_mgr.h:638
isc::data::ConstElementPtr statisticSetMaxSampleCountAllHandler(const isc::data::ConstElementPtr &params)
Handles statistic-sample-count-set-all command.
Evaluation context, an interface to the expression evaluation.
static void destroy()
Destroy lease manager.
const isc::log::MessageID DHCP4_DB_RECONNECT_NO_DB_CTL
const isc::log::MessageID DHCP4_DB_RECONNECT_FAILED
Manages a pool of asynchronous interval timers.
Definition: timer_mgr.h:62
boost::shared_ptr< SrvConfig > SrvConfigPtr
Non-const pointer to the SrvConfig.
Definition: srv_config.h:1036
The network state is being altered by the DB connection recovery mechanics.
ConstElementPtr redactConfig(ConstElementPtr const &element, list< string > const &json_path)
Redact a configuration.
const isc::log::MessageID DHCP4_CB_ON_DEMAND_FETCH_UPDATES_FAIL
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition: macros.h:32
const isc::log::MessageID DHCP4_MULTI_THREADING_INFO
const int CONTROL_RESULT_ERROR
Status code indicating a general failure.
boost::shared_ptr< Element > ElementPtr
Definition: data.h:20
STL namespace.
const isc::log::MessageID DHCP4_CONFIG_PACKET_QUEUE
const isc::log::MessageID DHCP4_CONFIG_UNSUPPORTED_OBJECT
uint16_t getServerPort() const
Get UDP port on which server should listen.
Definition: dhcp4_srv.h:399
static DbCallback db_failed_callback_
Optional callback function to invoke if an opened connection recovery failed.
Statistics Manager class.
isc::data::ConstElementPtr configureDhcp4Server(Dhcpv4Srv &server, isc::data::ConstElementPtr config_set, bool check_only)
Configure DHCPv4 server (Dhcpv4Srv) with a set of configuration values.
std::vector< HookLibInfo > HookLibsCollection
A storage for information about hook libraries.
Definition: libinfo.h:31
const int CONTROL_RESULT_EMPTY
Status code indicating that the specified command was completed correctly, but failed to produce any ...
isc::log::Logger dhcp4_logger(DHCP4_APP_LOGGER_NAME)
Base logger for DHCPv4 server.
Definition: dhcp4_log.h:90
Origin
Origin of the network state transition.
Definition: network_state.h:84
const isc::log::MessageID DHCP4_DB_RECONNECT_SUCCEEDED
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
static const std::string FLUSH_RECLAIMED_TIMER_NAME
Name of the timer for flushing reclaimed leases.
asiolink::IOServicePtr & getIOService()
Returns pointer to the IO service used by the server.
Definition: dhcp4_srv.h:292
Definition: edns.h:19
virtual ~ControlledDhcpv4Srv()
Destructor.
boost::shared_ptr< CfgDbAccess > CfgDbAccessPtr
A pointer to the CfgDbAccess.
static void create()
Creates new instance of the HostMgr.
Definition: host_mgr.cc:43
const isc::log::MessageID DHCP4_CB_PERIODIC_FETCH_UPDATES_FAIL
static DbCallback db_recovered_callback_
Optional callback function to invoke if an opened connection recovery succeeded.
const isc::log::MessageID DHCP4_DYNAMIC_RECONFIGURATION
boost::shared_ptr< const Element > ConstElementPtr
Definition: data.h:23
isc::data::ConstElementPtr redactConfig(isc::data::ConstElementPtr const &config)
Redact a configuration.
Definition: daemon.cc:257
void cleanup()
Performs cleanup, immediately before termination.
const isc::log::MessageID DHCP4_CONFIG_UNRECOVERABLE_ERROR
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
boost::shared_ptr< AllocEngine > alloc_engine_
Allocation Engine.
Definition: dhcp4_srv.h:1107
This is a base class for exceptions thrown from the DNS library module.
ConstElementPtr parseAnswer(int &rcode, const ConstElementPtr &msg)
Defines the logger used by the top-level component of kea-dhcp-ddns.
NetworkStatePtr network_state_
Holds information about disabled DHCP service and/or disabled subnet/network scopes.
Definition: dhcp4_srv.h:1114
void startD2()
Starts DHCP_DDNS client IO if DDNS updates are enabled.
Definition: dhcp4_srv.cc:3901
const isc::log::MessageID DHCP4_CB_PERIODIC_FETCH_UPDATES_RETRIES_EXHAUSTED
void setExitValue(int value)
Sets the exit value.
Definition: daemon.h:227
boost::shared_ptr< CalloutHandle > CalloutHandlePtr
A shared pointer to a CalloutHandle object.
static const std::string RECLAIM_EXPIRED_TIMER_NAME
Name of the timer for reclaiming expired leases.
const isc::log::MessageID DHCP4_CONFIG_RECEIVED
This file contains several functions and constants that are used for handling commands and responses ...
CtrlAgentHooks Hooks
const isc::log::MessageID DHCP4_HOOKS_LIBS_RELOAD_FAIL
const isc::log::MessageID DHCP4_CONFIG_LOAD_FAIL
A generic exception that is thrown if a function is called in a prohibited way.
const isc::log::MessageID DHCP4_NOT_RUNNING
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition: macros.h:14
isc::data::ConstElementPtr statisticSetMaxSampleAgeAllHandler(const isc::data::ConstElementPtr &params)
Handles statistic-sample-age-set-all command.
static ControlledDhcpv4Srv * getInstance()
Returns pointer to the sole instance of Dhcpv4Srv.
const isc::log::MessageID DHCP4_DB_RECONNECT_DISABLED
Controlled version of the DHCPv4 server.
std::string getConfigReport()
Definition: cfgrpt.cc:20
const StatsDuration & getMaxSampleAgeDefault() const
Get default duration limit.
Defines the Dhcp4o6Ipc class.
static void setIOService(const isc::asiolink::IOServicePtr &io_service)
Sets IO service to be used by the Lease Manager.
Definition: lease_mgr.h:753
uint32_t getMaxSampleCountDefault() const
Get default count limit.
const isc::log::MessageID DHCP4_COMMAND_RECEIVED
#define LOG_FATAL(LOGGER, MESSAGE)
Macro to conveniently test fatal output and log it.
Definition: macros.h:38
void shutdown() override
Instructs the server to shut down.
Definition: dhcp4_srv.cc:713
static const TimerMgrPtr & instance()
Returns pointer to the sole instance of the TimerMgr.
Definition: timer_mgr.cc:441
const int DBG_DHCP4_COMMAND
Debug level used to log receiving commands.
Definition: dhcp4_log.h:30
boost::shared_ptr< ReconnectCtl > ReconnectCtlPtr
Pointer to an instance of ReconnectCtl.
CBControlDHCPv4Ptr getCBControl() const
Returns an object which controls access to the configuration backends.
Definition: dhcp4_srv.h:306
NetworkStatePtr & getNetworkState()
Returns pointer to the network state used by the server.
Definition: dhcp4_srv.h:297
void shutdownServer(int exit_value)
Initiates shutdown procedure for the whole DHCPv4 server.
Contains declarations for loggers used by the DHCPv4 server component.
long toSeconds(const StatsDuration &dur)
Returns the number of seconds in a duration.
Definition: observation.h:45