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