Kea 3.1.3
ctrl_dhcp6_srv.cc
Go to the documentation of this file.
1// Copyright (C) 2014-2025 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
12#include <cc/data.h>
13#include <config/command_mgr.h>
18#include <dhcp/libdhcp++.h>
20#include <dhcp6/dhcp6_log.h>
21#include <dhcp6/dhcp6to4_ipc.h>
26#include <dhcpsrv/cfgmgr.h>
27#include <dhcpsrv/db_type.h>
28#include <dhcpsrv/host_mgr.h>
31#include <hooks/hooks.h>
32#include <hooks/hooks_manager.h>
34#include <stats/stats_mgr.h>
35#include <util/encode/encode.h>
37
38#include <signal.h>
39
40#include <sstream>
41
42using namespace isc::asiolink;
43using namespace isc::config;
44using namespace isc::data;
45using namespace isc::db;
46using namespace isc::dhcp;
47using namespace isc::hooks;
48using namespace isc::stats;
49using namespace isc::util;
50using namespace std;
51namespace ph = std::placeholders;
52
53namespace {
54
56struct CtrlDhcp6Hooks {
57 int hooks_index_dhcp6_srv_configured_;
58
60 CtrlDhcp6Hooks() {
61 hooks_index_dhcp6_srv_configured_ = HooksManager::registerHook("dhcp6_srv_configured");
62 }
63
64};
65
66// Declare a Hooks object. As this is outside any function or method, it
67// will be instantiated (and the constructor run) when the module is loaded.
68// As a result, the hook indexes will be defined before any method in this
69// module is called.
70CtrlDhcp6Hooks Hooks;
71
72// Name of the file holding server identifier.
73static const char* SERVER_DUID_FILE = "kea-dhcp6-serverid";
74
84void signalHandler(int signo) {
85 // SIGHUP signals a request to reconfigure the server.
86 if (signo == SIGHUP) {
88 } else if ((signo == SIGTERM) || (signo == SIGINT)) {
90 }
91}
92
93}
94
95namespace isc {
96namespace dhcp {
97
98ControlledDhcpv6Srv* ControlledDhcpv6Srv::server_ = NULL;
99
100void
101ControlledDhcpv6Srv::init(const std::string& file_name) {
102 // Keep the call timestamp.
103 start_ = boost::posix_time::second_clock::universal_time();
104
105 // Configure the server using JSON file.
106 ConstElementPtr result = loadConfigFile(file_name);
107
108 int rcode;
109 ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
110 if (rcode != CONTROL_RESULT_SUCCESS) {
111 string reason = comment ? comment->stringValue() :
112 "no details available";
113 isc_throw(isc::BadValue, reason);
114 }
115
116 // Set signal handlers. When the SIGHUP is received by the process
117 // the server reconfiguration will be triggered. When SIGTERM or
118 // SIGINT will be received, the server will start shutting down.
119 signal_set_.reset(new IOSignalSet(getIOService(), signalHandler));
120
121 signal_set_->add(SIGINT);
122 signal_set_->add(SIGHUP);
123 signal_set_->add(SIGTERM);
124}
125
127 signal_set_.reset();
128 getIOService()->poll();
129}
130
132ControlledDhcpv6Srv::loadConfigFile(const std::string& file_name) {
133 // This is a configuration backend implementation that reads the
134 // configuration from a JSON file.
135
138
139 // Basic sanity check: file name must not be empty.
140 try {
141 if (file_name.empty()) {
142 // Basic sanity check: file name must not be empty.
143 isc_throw(isc::BadValue, "JSON configuration file not specified."
144 " Please use -c command line option.");
145 }
146
147 // Read contents of the file and parse it as JSON
148 Parser6Context parser;
149 json = parser.parseFile(file_name, Parser6Context::PARSER_DHCP6);
150 if (!json) {
151 isc_throw(isc::BadValue, "no configuration found");
152 }
153
154 // Let's do sanity check before we call json->get() which
155 // works only for map.
156 if (json->getType() != isc::data::Element::map) {
157 isc_throw(isc::BadValue, "Configuration file is expected to be "
158 "a map, i.e., start with { and end with } and contain "
159 "at least an entry called 'Dhcp6' that itself is a map. "
160 << file_name
161 << " is a valid JSON, but its top element is not a map."
162 " Did you forget to add { } around your configuration?");
163 }
164
165 // Use parsed JSON structures to configure the server
166 result = CommandMgr::instance().processCommand(createCommand("config-set", json));
167 if (!result) {
168 // Undetermined status of the configuration. This should never
169 // happen, but as the configureDhcp6Server returns a pointer, it is
170 // theoretically possible that it will return NULL.
171 isc_throw(isc::BadValue, "undefined result of "
172 "process command \"config-set\"");
173 }
174
175 // Now check is the returned result is successful (rcode=0) or not
176 // (see @ref isc::config::parseAnswer).
177 int rcode;
178 ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
179 if (rcode != CONTROL_RESULT_SUCCESS) {
180 string reason = comment ? comment->stringValue() :
181 "no details available";
182 isc_throw(isc::BadValue, reason);
183 }
184 } catch (const std::exception& ex) {
185 // If configuration failed at any stage, we drop the staging
186 // configuration and continue to use the previous one.
188
190 .arg(file_name).arg(ex.what());
191 isc_throw(isc::BadValue, "configuration error using file '"
192 << file_name << "': " << ex.what());
193 }
194
196 .arg(MultiThreadingMgr::instance().getMode() ? "yes" : "no")
197 .arg(MultiThreadingMgr::instance().getThreadPoolSize())
198 .arg(MultiThreadingMgr::instance().getPacketQueueSize());
199
200 return (result);
201}
202
204ControlledDhcpv6Srv::commandShutdownHandler(const string&, ConstElementPtr args) {
207 return (createAnswer(CONTROL_RESULT_ERROR, "Shutdown failure."));
208 }
209
210 int exit_value = 0;
211 if (args) {
212 // @todo Should we go ahead and shutdown even if the args are invalid?
213 if (args->getType() != Element::map) {
214 return (createAnswer(CONTROL_RESULT_ERROR, "Argument must be a map"));
215 }
216
217 ConstElementPtr param = args->get("exit-value");
218 if (param) {
219 if (param->getType() != Element::integer) {
221 "parameter 'exit-value' is not an integer"));
222 }
223
224 exit_value = param->intValue();
225 }
226 }
227
229 return (createAnswer(CONTROL_RESULT_SUCCESS, "Shutting down."));
230}
231
233ControlledDhcpv6Srv::commandConfigReloadHandler(const string&,
234 ConstElementPtr /*args*/) {
235 // Get configuration file name.
237 try {
239 auto result = loadConfigFile(file);
241 return (result);
242 } catch (const std::exception& ex) {
243 // Log the unsuccessful reconfiguration. The reason for failure
244 // should be already logged. Don't rethrow an exception so as
245 // the server keeps working.
247 .arg(file);
249 "Config reload failed: " + string(ex.what())));
250 }
251}
252
254ControlledDhcpv6Srv::commandConfigGetHandler(const string&,
255 ConstElementPtr /*args*/) {
256 ElementPtr config = CfgMgr::instance().getCurrentCfg()->toElement();
257 string hash = BaseCommandMgr::getHash(config);
258 config->set("hash", Element::create(hash));
259
260 return (createAnswer(CONTROL_RESULT_SUCCESS, config));
261}
262
264ControlledDhcpv6Srv::commandConfigHashGetHandler(const string&,
265 ConstElementPtr /*args*/) {
266 ConstElementPtr config = CfgMgr::instance().getCurrentCfg()->toElement();
267
268 string hash = BaseCommandMgr::getHash(config);
269
271 params->set("hash", Element::create(hash));
272 return (createAnswer(CONTROL_RESULT_SUCCESS, params));
273}
274
276ControlledDhcpv6Srv::commandConfigWriteHandler(const string&,
277 ConstElementPtr args) {
278 string filename;
279
280 if (args) {
281 if (args->getType() != Element::map) {
282 return (createAnswer(CONTROL_RESULT_ERROR, "Argument must be a map"));
283 }
284 ConstElementPtr filename_param = args->get("filename");
285 if (filename_param) {
286 if (filename_param->getType() != Element::string) {
288 "passed parameter 'filename' is not a string"));
289 }
290 filename = filename_param->stringValue();
291 }
292 }
293
294 if (filename.empty()) {
295 // filename parameter was not specified, so let's use whatever we remember
296 // from the command-line
297 filename = getConfigFile();
298 if (filename.empty()) {
299 return (createAnswer(CONTROL_RESULT_ERROR, "Unable to determine filename."
300 "Please specify filename explicitly."));
301 }
302 } else {
303 try {
304 checkWriteConfigFile(filename);
305 } catch (const isc::Exception& ex) {
306 std::ostringstream msg;
307 msg << "not allowed to write config into " << filename
308 << ": " << ex.what();
309 return (createAnswer(CONTROL_RESULT_ERROR, msg.str()));
310 }
311 }
312
313 // Ok, it's time to write the file.
314 size_t size = 0;
315 try {
316 ConstElementPtr cfg = CfgMgr::instance().getCurrentCfg()->toElement();
317 size = writeConfigFile(filename, cfg);
318 } catch (const isc::Exception& ex) {
319 return (createAnswer(CONTROL_RESULT_ERROR, string("Error during config-write: ")
320 + ex.what()));
321 }
322 if (size == 0) {
323 return (createAnswer(CONTROL_RESULT_ERROR, "Error writing configuration to "
324 + filename));
325 }
326
327 // Ok, it's time to return the successful response.
329 params->set("size", Element::create(static_cast<long long>(size)));
330 params->set("filename", Element::create(filename));
331
332 return (createAnswer(CONTROL_RESULT_SUCCESS, "Configuration written to "
333 + filename + " successful", params));
334}
335
337ControlledDhcpv6Srv::commandConfigSetHandler(const string&,
338 ConstElementPtr args) {
339 const int status_code = CONTROL_RESULT_ERROR;
340 ConstElementPtr dhcp6;
341 string message;
342
343 // Command arguments are expected to be:
344 // { "Dhcp6": { ... } }
345 if (!args) {
346 message = "Missing mandatory 'arguments' parameter.";
347 } else {
348 dhcp6 = args->get("Dhcp6");
349 if (!dhcp6) {
350 message = "Missing mandatory 'Dhcp6' parameter.";
351 } else if (dhcp6->getType() != Element::map) {
352 message = "'Dhcp6' parameter expected to be a map.";
353 }
354 }
355
356 // Check unsupported objects.
357 if (message.empty()) {
358 for (auto const& obj : args->mapValue()) {
359 const string& obj_name = obj.first;
360 if (obj_name != "Dhcp6") {
362 .arg(obj_name);
363 if (message.empty()) {
364 message = "Unsupported '" + obj_name + "' parameter";
365 } else {
366 message += " (and '" + obj_name + "')";
367 }
368 }
369 }
370 if (!message.empty()) {
371 message += ".";
372 }
373 }
374
375 if (!message.empty()) {
376 // Something is amiss with arguments, return a failure response.
377 ConstElementPtr result = isc::config::createAnswer(status_code,
378 message);
379 return (result);
380 }
381
382 ConstElementPtr lease_database = dhcp6->get("lease-database");
383 if (lease_database) {
384 db::DbAccessParser parser;
385 std::string access_string;
386 parser.parse(access_string, lease_database);
387 auto params = parser.getDbAccessParameters();
388 if (params["type"] == "memfile") {
389 string file_name = params["name"];
392 "Can not update configuration while lease file cleanup process is running."));
393 }
394 }
395 }
396
397 // stop thread pool (if running)
398 MultiThreadingCriticalSection cs;
399
400 // We are starting the configuration process so we should remove any
401 // staging configuration that has been created during previous
402 // configuration attempts.
404
405 // Parse the logger configuration explicitly into the staging config.
406 // Note this does not alter the current loggers, they remain in
407 // effect until we apply the logging config below. If no logging
408 // is supplied logging will revert to default logging.
409 Daemon::configureLogger(dhcp6, CfgMgr::instance().getStagingCfg());
410
411 // Let's apply the new logging. We do it early, so we'll be able to print
412 // out what exactly is wrong with the new config in case of problems.
413 CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
414
415 // Now we configure the server proper.
416 ConstElementPtr result = processConfig(dhcp6);
417
418 // If the configuration parsed successfully, apply the new logger
419 // configuration and then commit the new configuration. We apply
420 // the logging first in case there's a configuration failure.
421 int rcode = 0;
422 isc::config::parseAnswer(rcode, result);
423 if (rcode == CONTROL_RESULT_SUCCESS) {
424 CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
425
426 // Use new configuration.
428 } else if (CfgMgr::instance().getCurrentCfg()->getSequence() != 0) {
429 // Ok, we applied the logging from the upcoming configuration, but
430 // there were problems with the config. As such, we need to back off
431 // and revert to the previous logging configuration. This is not done if
432 // sequence == 0, because that would mean always reverting to stdout by
433 // default, and it is arguably more helpful to have the error in a
434 // potential file or syslog configured in the upcoming configuration.
435 CfgMgr::instance().getCurrentCfg()->applyLoggingCfg();
436
437 // Not initial configuration so someone can believe we reverted
438 // to the previous configuration. It is not the case so be clear
439 // about this.
441 }
442
444 try {
445 // Handle events registered by hooks using external IOService objects.
447 } catch (const std::exception& ex) {
448 std::ostringstream err;
449 err << "Error initializing hooks: "
450 << ex.what();
452 }
453
454 return (result);
455}
456
458ControlledDhcpv6Srv::commandConfigTestHandler(const string&,
459 ConstElementPtr args) {
460 const int status_code = CONTROL_RESULT_ERROR; // 1 indicates an error
461 ConstElementPtr dhcp6;
462 string message;
463
464 // Command arguments are expected to be:
465 // { "Dhcp6": { ... } }
466 if (!args) {
467 message = "Missing mandatory 'arguments' parameter.";
468 } else {
469 dhcp6 = args->get("Dhcp6");
470 if (!dhcp6) {
471 message = "Missing mandatory 'Dhcp6' parameter.";
472 } else if (dhcp6->getType() != Element::map) {
473 message = "'Dhcp6' parameter expected to be a map.";
474 }
475 }
476
477 // Check unsupported objects.
478 if (message.empty()) {
479 for (auto const& obj : args->mapValue()) {
480 const string& obj_name = obj.first;
481 if (obj_name != "Dhcp6") {
483 .arg(obj_name);
484 if (message.empty()) {
485 message = "Unsupported '" + obj_name + "' parameter";
486 } else {
487 message += " (and '" + obj_name + "')";
488 }
489 }
490 }
491 if (!message.empty()) {
492 message += ".";
493 }
494 }
495
496 if (!message.empty()) {
497 // Something is amiss with arguments, return a failure response.
498 ConstElementPtr result = isc::config::createAnswer(status_code,
499 message);
500 return (result);
501 }
502
503 // stop thread pool (if running)
504 MultiThreadingCriticalSection cs;
505
506 // We are starting the configuration process so we should remove any
507 // staging configuration that has been created during previous
508 // configuration attempts.
510
511 // Now we check the server proper.
512 return (checkConfig(dhcp6));
513}
514
516ControlledDhcpv6Srv::commandDhcpDisableHandler(const std::string&,
517 ConstElementPtr args) {
518 std::ostringstream message;
519 int64_t max_period = 0;
520 std::string origin;
521
522 // If the args map does not contain 'origin' parameter, the default type
523 // will be used (user command).
524 auto type = NetworkState::USER_COMMAND;
525
526 // Parse arguments to see if the 'max-period' or 'origin' parameters have
527 // been specified.
528 if (args) {
529 // Arguments must be a map.
530 if (args->getType() != Element::map) {
531 message << "arguments for the 'dhcp-disable' command must be a map";
532
533 } else {
534 ConstElementPtr max_period_element = args->get("max-period");
535 // max-period is optional.
536 if (max_period_element) {
537 // It must be an integer, if specified.
538 if (max_period_element->getType() != Element::integer) {
539 message << "'max-period' argument must be a number";
540
541 } else {
542 // It must be positive integer.
543 max_period = max_period_element->intValue();
544 if (max_period <= 0) {
545 message << "'max-period' must be positive integer";
546 }
547 }
548 }
549 // 'origin-id' replaces the older parameter 'origin' since Kea 2.5.8
550 // stable release. However, the 'origin' is kept for backward compatibility
551 // with Kea versions before 2.5.8. It is common to receive both parameters
552 // because HA hook library sends both in case the partner server hasn't been
553 // upgraded to the new version. The 'origin-id' takes precedence over the
554 // 'origin'.
555 ConstElementPtr origin_id_element = args->get("origin-id");
556 ConstElementPtr origin_element = args->get("origin");
557 // The 'origin-id' and 'origin' arguments are optional.
558 if (origin_id_element) {
559 if (origin_id_element->getType() == Element::integer) {
560 type = origin_id_element->intValue();
561 } else {
562 message << "'origin-id' argument must be a number";
563 }
564 } else if (origin_element) {
565 switch (origin_element->getType()) {
566 case Element::string:
567 origin = origin_element->stringValue();
568 if (origin == "ha-partner") {
570 } else if (origin != "user") {
571 if (origin.empty()) {
572 origin = "(empty string)";
573 }
574 message << "invalid value used for 'origin' parameter: "
575 << origin;
576 }
577 break;
578 case Element::integer:
579 type = origin_element->intValue();
580 break;
581 default:
582 // It must be a string or a number, if specified.
583 message << "'origin' argument must be a string or a number";
584 }
585 }
586 }
587 }
588
589 // No error occurred, so let's disable the service.
590 if (message.tellp() == 0) {
591 message << "DHCPv6 service disabled";
592 if (max_period > 0) {
593 message << " for " << max_period << " seconds";
594
595 // The user specified that the DHCP service should resume not
596 // later than in max-period seconds. If the 'dhcp-enable' command
597 // is not sent, the DHCP service will resume automatically.
598 network_state_->delayedEnableService(static_cast<unsigned>(max_period),
599 type);
600 }
601 network_state_->disableService(type);
602
603 // Success.
604 return (config::createAnswer(CONTROL_RESULT_SUCCESS, message.str()));
605 }
606
607 // Failure.
608 return (config::createAnswer(CONTROL_RESULT_ERROR, message.str()));
609}
610
612ControlledDhcpv6Srv::commandDhcpEnableHandler(const std::string&,
613 ConstElementPtr args) {
614 std::ostringstream message;
615 std::string origin;
616
617 // If the args map does not contain 'origin' parameter, the default type
618 // will be used (user command).
619 auto type = NetworkState::USER_COMMAND;
620
621 // Parse arguments to see if the 'origin' parameter has been specified.
622 if (args) {
623 // Arguments must be a map.
624 if (args->getType() != Element::map) {
625 message << "arguments for the 'dhcp-enable' command must be a map";
626
627 } else {
628 // 'origin-id' replaces the older parameter 'origin' since Kea 2.5.8
629 // stable release. However, the 'origin' is kept for backward compatibility
630 // with Kea versions before 2.5.8. It is common to receive both parameters
631 // because HA hook library sends both in case the partner server hasn't been
632 // upgraded to the new version. The 'origin-id' takes precedence over the
633 // 'origin'.
634 ConstElementPtr origin_id_element = args->get("origin-id");
635 ConstElementPtr origin_element = args->get("origin");
636 // The 'origin-id' and 'origin' arguments are optional.
637 if (origin_id_element) {
638 if (origin_id_element->getType() == Element::integer) {
639 type = origin_id_element->intValue();
640 } else {
641 message << "'origin-id' argument must be a number";
642 }
643 } else if (origin_element) {
644 switch (origin_element->getType()) {
645 case Element::string:
646 origin = origin_element->stringValue();
647 if (origin == "ha-partner") {
649 } else if (origin != "user") {
650 if (origin.empty()) {
651 origin = "(empty string)";
652 }
653 message << "invalid value used for 'origin' parameter: "
654 << origin;
655 }
656 break;
657 case Element::integer:
658 type = origin_element->intValue();
659 break;
660 default:
661 // It must be a string or a number, if specified.
662 message << "'origin' argument must be a string or a number";
663 }
664 }
665 }
666 }
667
668 // No error occurred, so let's enable the service.
669 if (message.tellp() == 0) {
670 network_state_->enableService(type);
671
672 // Success.
674 "DHCP service successfully enabled"));
675 }
676
677 // Failure.
678 return (config::createAnswer(CONTROL_RESULT_ERROR, message.str()));
679}
680
682ControlledDhcpv6Srv::commandVersionGetHandler(const string&, ConstElementPtr) {
684 ElementPtr arguments = Element::createMap();
685 arguments->set("extended", extended);
688 arguments);
689 return (answer);
690}
691
693ControlledDhcpv6Srv::commandBuildReportHandler(const string&,
695 ConstElementPtr answer =
697 return (answer);
698}
699
701ControlledDhcpv6Srv::commandLeasesReclaimHandler(const string&,
702 ConstElementPtr args) {
703 int status_code = CONTROL_RESULT_ERROR;
704 string message;
705
706 // args must be { "remove": <bool> }
707 if (!args) {
708 message = "Missing mandatory 'remove' parameter.";
709 } else {
710 ConstElementPtr remove_name = args->get("remove");
711 if (!remove_name) {
712 message = "Missing mandatory 'remove' parameter.";
713 } else if (remove_name->getType() != Element::boolean) {
714 message = "'remove' parameter expected to be a boolean.";
715 } else {
716 bool remove_lease = remove_name->boolValue();
717 server_->alloc_engine_->reclaimExpiredLeases6(0, 0, remove_lease);
718 status_code = 0;
719 message = "Reclamation of expired leases is complete.";
720 }
721 }
722 ConstElementPtr answer = isc::config::createAnswer(status_code, message);
723 return (answer);
724}
725
727ControlledDhcpv6Srv::commandSubnet6SelectTestHandler(const string&,
728 ConstElementPtr args) {
729 if (!args) {
730 return (createAnswer(CONTROL_RESULT_ERROR, "empty arguments"));
731 }
732 if (args->getType() != Element::map) {
733 return (createAnswer(CONTROL_RESULT_ERROR, "arguments must be a map"));
734 }
735 SubnetSelector selector;
737 for (auto const& entry : args->mapValue()) {
738 ostringstream errmsg;
739 if (entry.first == "interface") {
740 if (entry.second->getType() != Element::string) {
741 errmsg << "'interface' entry must be a string";
742 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
743 }
744 selector.iface_name_ = entry.second->stringValue();
745 continue;
746 } if (entry.first == "interface-id") {
747 if (entry.second->getType() != Element::string) {
748 errmsg << "'interface-id' entry must be a string";
749 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
750 }
751 try {
752 string str = entry.second->stringValue();
753 vector<uint8_t> id = util::str::quotedStringToBinary(str);
754 if (id.empty()) {
756 }
757 if (id.empty()) {
758 errmsg << "'interface-id' must be not empty";
759 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
760 }
761 selector.interface_id_ = OptionPtr(new Option(Option::V6,
763 id));
764 continue;
765 } catch (...) {
766 errmsg << "value of 'interface-id' was not recognized";
767 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
768 }
769 } else if (entry.first == "remote") {
770 if (entry.second->getType() != Element::string) {
771 errmsg << "'remote' entry must be a string";
772 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
773 }
774 try {
775 IOAddress addr(entry.second->stringValue());
776 if (!addr.isV6()) {
777 errmsg << "bad 'remote' entry: not IPv6";
778 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
779 }
780 selector.remote_address_ = addr;
781 continue;
782 } catch (const exception& ex) {
783 errmsg << "bad 'remote' entry: " << ex.what();
784 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
785 }
786 } else if (entry.first == "link") {
787 if (entry.second->getType() != Element::string) {
788 errmsg << "'link' entry must be a string";
789 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
790 }
791 try {
792 IOAddress addr(entry.second->stringValue());
793 if (!addr.isV6()) {
794 errmsg << "bad 'link' entry: not IPv6";
795 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
796 }
797 selector.first_relay_linkaddr_ = addr;
798 continue;
799 } catch (const exception& ex) {
800 errmsg << "bad 'link' entry: " << ex.what();
801 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
802 }
803 } else if (entry.first == "classes") {
804 if (entry.second->getType() != Element::list) {
806 "'classes' entry must be a list"));
807 }
808 for (auto const& item : entry.second->listValue()) {
809 if (!item || (item->getType() != Element::string)) {
810 errmsg << "'classes' entry must be a list of strings";
811 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
812 }
813 // Skip empty client classes.
814 if (!item->stringValue().empty()) {
815 selector.client_classes_.insert(item->stringValue());
816 }
817 }
818 continue;
819 } else {
820 errmsg << "unknown entry '" << entry.first << "'";
821 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
822 }
823 }
825 getCfgSubnets6()->selectSubnet(selector);
826 if (!subnet) {
827 return (createAnswer(CONTROL_RESULT_EMPTY, "no subnet selected"));
828 }
829 SharedNetwork6Ptr network;
830 subnet->getSharedNetwork(network);
831 ostringstream msg;
832 if (network) {
833 msg << "selected shared network '" << network->getName()
834 << "' starting with subnet '" << subnet->toText()
835 << "' id " << subnet->getID();
836 } else {
837 msg << "selected subnet '" << subnet->toText()
838 << "' id " << subnet->getID();
839 }
840 return (createAnswer(CONTROL_RESULT_SUCCESS, msg.str()));
841}
842
844ControlledDhcpv6Srv::commandServerTagGetHandler(const std::string&,
846 const std::string& tag =
847 CfgMgr::instance().getCurrentCfg()->getServerTag();
848 ElementPtr response = Element::createMap();
849 response->set("server-tag", Element::create(tag));
850
851 return (createAnswer(CONTROL_RESULT_SUCCESS, response));
852}
853
855ControlledDhcpv6Srv::commandConfigBackendPullHandler(const std::string&,
857 auto ctl_info = CfgMgr::instance().getCurrentCfg()->getConfigControlInfo();
858 if (!ctl_info) {
859 return (createAnswer(CONTROL_RESULT_EMPTY, "No config backend."));
860 }
861
862 // stop thread pool (if running)
863 MultiThreadingCriticalSection cs;
864
865 // Reschedule the periodic CB fetch.
866 if (TimerMgr::instance()->isTimerRegistered("Dhcp6CBFetchTimer")) {
867 TimerMgr::instance()->cancel("Dhcp6CBFetchTimer");
868 TimerMgr::instance()->setup("Dhcp6CBFetchTimer");
869 }
870
871 // Code from cbFetchUpdates.
872 // The configuration to use is the current one because this is called
873 // after the configuration manager commit.
874 try {
875 auto srv_cfg = CfgMgr::instance().getCurrentCfg();
876 auto mode = CBControlDHCPv6::FetchMode::FETCH_UPDATE;
877 server_->getCBControl()->databaseConfigFetch(srv_cfg, mode);
878 } catch (const std::exception& ex) {
880 .arg(ex.what());
882 "On demand configuration update failed: " +
883 string(ex.what())));
884 }
886 "On demand configuration update successful."));
887}
888
890ControlledDhcpv6Srv::commandStatusGetHandler(const string&,
891 ConstElementPtr /*args*/) {
893 status->set("pid", Element::create(static_cast<int>(getpid())));
894
895 auto now = boost::posix_time::second_clock::universal_time();
896 // Sanity check: start_ is always initialized.
897 if (!start_.is_not_a_date_time()) {
898 auto uptime = now - start_;
899 status->set("uptime", Element::create(uptime.total_seconds()));
900 }
901
902 auto last_commit = CfgMgr::instance().getCurrentCfg()->getLastCommitTime();
903 if (!last_commit.is_not_a_date_time()) {
904 auto reload = now - last_commit;
905 status->set("reload", Element::create(reload.total_seconds()));
906 }
907
908 auto& mt_mgr = MultiThreadingMgr::instance();
909 if (mt_mgr.getMode()) {
910 status->set("multi-threading-enabled", Element::create(true));
911 status->set("thread-pool-size", Element::create(static_cast<int32_t>(
912 MultiThreadingMgr::instance().getThreadPoolSize())));
913 status->set("packet-queue-size", Element::create(static_cast<int32_t>(
914 MultiThreadingMgr::instance().getPacketQueueSize())));
915 ElementPtr queue_stats = Element::createList();
916 queue_stats->add(Element::create(mt_mgr.getThreadPool().getQueueStat(10)));
917 queue_stats->add(Element::create(mt_mgr.getThreadPool().getQueueStat(100)));
918 queue_stats->add(Element::create(mt_mgr.getThreadPool().getQueueStat(1000)));
919 status->set("packet-queue-statistics", queue_stats);
920
921 } else {
922 status->set("multi-threading-enabled", Element::create(false));
923 }
924
925 // Merge lease manager status.
926 ElementPtr lm_info;
929 }
930 if (lm_info && (lm_info->getType() == Element::map)) {
931 for (auto const& entry : lm_info->mapValue()) {
932 status->set(entry.first, entry.second);
933 }
934 }
935
936 status->set("extended-info-tables", Element::create(
937 CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getExtendedInfoTablesEnabled()));
938
939 // Iterate through the interfaces and get all the errors.
940 ElementPtr socket_errors(Element::createList());
941 for (IfacePtr const& interface : IfaceMgr::instance().getIfaces()) {
942 for (std::string const& error : interface->getErrors()) {
943 socket_errors->add(Element::create(error));
944 }
945 }
946
947 // Abstract the information from all sockets into a single status.
949 if (socket_errors->empty()) {
950 sockets->set("status", Element::create("ready"));
951 } else {
952 ReconnectCtlPtr const reconnect_ctl(
953 CfgMgr::instance().getCurrentCfg()->getCfgIface()->getReconnectCtl());
954 if (reconnect_ctl && reconnect_ctl->retriesLeft()) {
955 sockets->set("status", Element::create("retrying"));
956 } else {
957 sockets->set("status", Element::create("failed"));
958 }
959 sockets->set("errors", socket_errors);
960 }
961 status->set("sockets", sockets);
962
963 status->set("dhcp-state", network_state_->toElement());
964
965 return (createAnswer(CONTROL_RESULT_SUCCESS, status));
966}
967
969ControlledDhcpv6Srv::commandStatisticSetMaxSampleCountAllHandler(const string&,
970 ConstElementPtr args) {
971 StatsMgr& stats_mgr = StatsMgr::instance();
973 // Update the default parameter.
974 long max_samples = stats_mgr.getMaxSampleCountDefault();
975 CfgMgr::instance().getCurrentCfg()->addConfiguredGlobal(
976 "statistic-default-sample-count", Element::create(max_samples));
977 return (answer);
978}
979
981ControlledDhcpv6Srv::commandStatisticSetMaxSampleAgeAllHandler(const string&,
982 ConstElementPtr args) {
983 StatsMgr& stats_mgr = StatsMgr::instance();
985 // Update the default parameter.
986 auto duration = stats_mgr.getMaxSampleAgeDefault();
987 long max_age = toSeconds(duration);
988 CfgMgr::instance().getCurrentCfg()->addConfiguredGlobal(
989 "statistic-default-sample-age", Element::create(max_age));
990 return (answer);
991}
992
994ControlledDhcpv6Srv::commandLfcStartHandler(const string&, ConstElementPtr) {
996 return (LeaseMgrFactory::instance().lfcStartHandler());
997 }
999 "no lease backend"));
1000}
1001
1005
1006 // Allow DB reconnect on startup. The database connection parameters specify
1007 // respective details.
1009
1010 // Single stream instance used in all error clauses
1011 std::ostringstream err;
1012
1013 if (!srv) {
1014 err << "Server object not initialized, can't process config.";
1016 }
1017
1019 .arg(srv->redactConfig(config)->str());
1020
1021 // Destroy lease manager before hooks unload.
1023
1024 // Destroy host manager before hooks unload.
1026
1028
1029 // Check that configuration was successful. If not, do not reopen sockets
1030 // and don't bother with DDNS stuff.
1031 try {
1032 int rcode = 0;
1033 isc::config::parseAnswer(rcode, answer);
1034 if (rcode != 0) {
1035 return (answer);
1036 }
1037 } catch (const std::exception& ex) {
1038 err << "Failed to process configuration:" << ex.what();
1040 }
1041
1042 // Re-open lease and host database with new parameters.
1043 try {
1045 std::bind(&ControlledDhcpv6Srv::dbLostCallback, srv, ph::_1);
1046
1048 std::bind(&ControlledDhcpv6Srv::dbRecoveredCallback, srv, ph::_1);
1049
1051 std::bind(&ControlledDhcpv6Srv::dbFailedCallback, srv, ph::_1);
1052
1053 CfgDbAccessPtr cfg_db = CfgMgr::instance().getStagingCfg()->getCfgDbAccess();
1054 string params = "universe=6";
1055 if (cfg_db->getExtendedInfoTablesEnabled()) {
1056 params += " extended-info-tables=true";
1057 }
1058 cfg_db->setAppendedParameters(params);
1059 cfg_db->createManagers();
1060 // Reset counters related to connections as all managers have been recreated.
1061 srv->getNetworkState()->resetForDbConnection();
1062 srv->getNetworkState()->resetForLocalCommands();
1063 srv->getNetworkState()->resetForRemoteCommands();
1064 } catch (const std::exception& ex) {
1065 err << "Unable to open database: " << ex.what();
1067 }
1068
1069 // Regenerate server identifier if needed.
1070 try {
1071 const std::string duid_file =
1072 std::string(CfgMgr::instance().getDataDir()) + "/" +
1073 std::string(SERVER_DUID_FILE);
1074 DuidPtr duid = CfgMgr::instance().getStagingCfg()->getCfgDUID()->create(duid_file);
1075 server_->serverid_.reset(new Option(Option::V6, D6O_SERVERID, duid->getDuid()));
1076 if (duid) {
1078 .arg(duid->toText())
1079 .arg(duid_file);
1080 }
1081
1082 } catch (const std::exception& ex) {
1083 err << "unable to configure server identifier: " << ex.what();
1085 }
1086
1087 // Server will start DDNS communications if its enabled.
1088 try {
1089 srv->startD2();
1090 } catch (const std::exception& ex) {
1091 err << "Error starting DHCP_DDNS client after server reconfiguration: "
1092 << ex.what();
1094 }
1095
1096 // Setup DHCPv4-over-DHCPv6 IPC
1097 try {
1099 } catch (const std::exception& ex) {
1100 err << "error starting DHCPv4-over-DHCPv6 IPC "
1101 " after server reconfiguration: " << ex.what();
1103 }
1104
1105 // Configure DHCP packet queueing
1106 try {
1108 qc = CfgMgr::instance().getStagingCfg()->getDHCPQueueControl();
1109 if (IfaceMgr::instance().configureDHCPPacketQueue(AF_INET6, qc)) {
1111 .arg(IfaceMgr::instance().getPacketQueue6()->getInfoStr());
1112 }
1113
1114 } catch (const std::exception& ex) {
1115 err << "Error setting packet queue controls after server reconfiguration: "
1116 << ex.what();
1118 }
1119
1120 // Configure a callback to shut down the server when the bind socket
1121 // attempts exceeded.
1123 std::bind(&ControlledDhcpv6Srv::openSocketsFailedCallback, srv, ph::_1);
1124
1125 // Configuration may change active interfaces. Therefore, we have to reopen
1126 // sockets according to new configuration. It is possible that this
1127 // operation will fail for some interfaces but the openSockets function
1128 // guards against exceptions and invokes a callback function to
1129 // log warnings. Since we allow that this fails for some interfaces there
1130 // is no need to rollback configuration if socket fails to open on any
1131 // of the interfaces.
1132 CfgMgr::instance().getStagingCfg()->getCfgIface()->
1133 openSockets(AF_INET6, srv->getServerPort());
1134
1135 // Install the timers for handling leases reclamation.
1136 try {
1137 CfgMgr::instance().getStagingCfg()->getCfgExpiration()->
1138 setupTimers(&ControlledDhcpv6Srv::reclaimExpiredLeases,
1139 &ControlledDhcpv6Srv::deleteExpiredReclaimedLeases,
1140 server_);
1141
1142 } catch (const std::exception& ex) {
1143 err << "unable to setup timers for periodically running the"
1144 " reclamation of the expired leases: "
1145 << ex.what() << ".";
1147 }
1148
1149 // Setup config backend polling, if configured for it.
1150 auto ctl_info = CfgMgr::instance().getStagingCfg()->getConfigControlInfo();
1151 if (ctl_info) {
1152 long fetch_time = static_cast<long>(ctl_info->getConfigFetchWaitTime());
1153 // Only schedule the CB fetch timer if the fetch wait time is greater
1154 // than 0.
1155 if (fetch_time > 0) {
1156 // When we run unit tests, we want to use milliseconds unit for the
1157 // specified interval. Otherwise, we use seconds. Note that using
1158 // milliseconds as a unit in unit tests prevents us from waiting 1
1159 // second on more before the timer goes off. Instead, we wait one
1160 // millisecond which significantly reduces the test time.
1161 if (!server_->inTestMode()) {
1162 fetch_time = 1000 * fetch_time;
1163 }
1164
1165 boost::shared_ptr<unsigned> failure_count(new unsigned(0));
1167 registerTimer("Dhcp6CBFetchTimer",
1168 std::bind(&ControlledDhcpv6Srv::cbFetchUpdates,
1169 server_, CfgMgr::instance().getStagingCfg(),
1170 failure_count),
1171 fetch_time,
1173 TimerMgr::instance()->setup("Dhcp6CBFetchTimer");
1174 }
1175 }
1176
1177 // Finally, we can commit runtime option definitions in libdhcp++. This is
1178 // exception free.
1180
1182 if (notify_libraries) {
1183 return (notify_libraries);
1184 }
1185
1186 // Initialize the allocators. If the user selected a Free Lease Queue Allocator
1187 // for any of the subnets, the server will now populate free leases to the queue.
1188 // It may take a while!
1189 try {
1190 CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->initAllocatorsAfterConfigure();
1191
1192 } catch (const std::exception& ex) {
1193 err << "Error initializing the lease allocators: "
1194 << ex.what();
1196 }
1197
1198 // Apply multi threading settings.
1199 // @note These settings are applied/updated only if no errors occur while
1200 // applying the new configuration.
1201 // @todo This should be fixed.
1202 try {
1203 CfgMultiThreading::apply(CfgMgr::instance().getStagingCfg()->getDHCPMultiThreading());
1204 } catch (const std::exception& ex) {
1205 err << "Error applying multi threading settings: "
1206 << ex.what();
1208 }
1209
1210 return (answer);
1211}
1212
1216 // This hook point notifies hooks libraries that the configuration of the
1217 // DHCPv6 server has completed. It provides the hook library with the pointer
1218 // to the common IO service object, new server configuration in the JSON
1219 // format and with the pointer to the configuration storage where the
1220 // parsed configuration is stored.
1221 if (HooksManager::calloutsPresent(Hooks.hooks_index_dhcp6_srv_configured_)) {
1223
1224 callout_handle->setArgument("io_context", srv->getIOService());
1225 callout_handle->setArgument("network_state", srv->getNetworkState());
1226 callout_handle->setArgument("json_config", config);
1227 callout_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
1228
1229 HooksManager::callCallouts(Hooks.hooks_index_dhcp6_srv_configured_,
1230 *callout_handle);
1231
1232 // If next step is DROP, report a configuration error.
1233 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1234 string error;
1235 try {
1236 callout_handle->getArgument("error", error);
1237 } catch (NoSuchArgument const& ex) {
1238 error = "unknown error";
1239 }
1241 }
1242 }
1243
1244 return (ConstElementPtr());
1245}
1246
1250
1251 if (!srv) {
1253 "Server object not initialized, can't process config.");
1254 return (no_srv);
1255 }
1256
1258 .arg(srv->redactConfig(config)->str());
1259
1260 return (configureDhcp6Server(*srv, config, true));
1261}
1262
1263ControlledDhcpv6Srv::ControlledDhcpv6Srv(uint16_t server_port /*= DHCP6_SERVER_PORT*/,
1264 uint16_t client_port /*= 0*/)
1265 : Dhcpv6Srv(server_port, client_port), timer_mgr_(TimerMgr::instance()) {
1266 if (getInstance()) {
1268 "There is another Dhcpv6Srv instance already.");
1269 }
1270 server_ = this; // remember this instance for later use in handlers
1271
1272 // ProcessSpawn uses IO service to handle signal set events.
1274
1275 // TimerMgr uses IO service to run asynchronous timers.
1276 TimerMgr::instance()->setIOService(getIOService());
1277
1278 // Command managers use IO service to run asynchronous socket operations.
1281
1282 // Set the HTTP default socket address to the IPv6 (vs IPv4) loopback.
1284
1285 // Set the HTTP authentication default realm.
1287
1288 // DatabaseConnection uses IO service to run asynchronous timers.
1290
1291 // These are the commands always supported by the DHCPv6 server.
1292 // Please keep the list in alphabetic order.
1293 CommandMgr::instance().registerCommand("build-report",
1294 std::bind(&ControlledDhcpv6Srv::commandBuildReportHandler, this, ph::_1, ph::_2));
1295
1296 CommandMgr::instance().registerCommand("config-backend-pull",
1297 std::bind(&ControlledDhcpv6Srv::commandConfigBackendPullHandler, this, ph::_1, ph::_2));
1298
1300 std::bind(&ControlledDhcpv6Srv::commandConfigGetHandler, this, ph::_1, ph::_2));
1301
1302 CommandMgr::instance().registerCommand("config-hash-get",
1303 std::bind(&ControlledDhcpv6Srv::commandConfigHashGetHandler, this, ph::_1, ph::_2));
1304
1305 CommandMgr::instance().registerCommand("config-reload",
1306 std::bind(&ControlledDhcpv6Srv::commandConfigReloadHandler, this, ph::_1, ph::_2));
1307
1309 std::bind(&ControlledDhcpv6Srv::commandConfigSetHandler, this, ph::_1, ph::_2));
1310
1311 CommandMgr::instance().registerCommand("config-test",
1312 std::bind(&ControlledDhcpv6Srv::commandConfigTestHandler, this, ph::_1, ph::_2));
1313
1314 CommandMgr::instance().registerCommand("config-write",
1315 std::bind(&ControlledDhcpv6Srv::commandConfigWriteHandler, this, ph::_1, ph::_2));
1316
1317 CommandMgr::instance().registerCommand("dhcp-enable",
1318 std::bind(&ControlledDhcpv6Srv::commandDhcpEnableHandler, this, ph::_1, ph::_2));
1319
1320 CommandMgr::instance().registerCommand("dhcp-disable",
1321 std::bind(&ControlledDhcpv6Srv::commandDhcpDisableHandler, this, ph::_1, ph::_2));
1322
1323 CommandMgr::instance().registerCommand("kea-lfc-start",
1324 std::bind(&ControlledDhcpv6Srv::commandLfcStartHandler, this, ph::_1, ph::_2));
1325
1326 CommandMgr::instance().registerCommand("leases-reclaim",
1327 std::bind(&ControlledDhcpv6Srv::commandLeasesReclaimHandler, this, ph::_1, ph::_2));
1328
1329 CommandMgr::instance().registerCommand("subnet6-select-test",
1330 std::bind(&ControlledDhcpv6Srv::commandSubnet6SelectTestHandler, this, ph::_1, ph::_2));
1331
1332 CommandMgr::instance().registerCommand("server-tag-get",
1333 std::bind(&ControlledDhcpv6Srv::commandServerTagGetHandler, this, ph::_1, ph::_2));
1334
1336 std::bind(&ControlledDhcpv6Srv::commandShutdownHandler, this, ph::_1, ph::_2));
1337
1339 std::bind(&ControlledDhcpv6Srv::commandStatusGetHandler, this, ph::_1, ph::_2));
1340
1341 CommandMgr::instance().registerCommand("version-get",
1342 std::bind(&ControlledDhcpv6Srv::commandVersionGetHandler, this, ph::_1, ph::_2));
1343
1344 // Register statistic related commands
1345 CommandMgr::instance().registerCommand("statistic-get",
1346 std::bind(&StatsMgr::statisticGetHandler, ph::_1, ph::_2));
1347
1348 CommandMgr::instance().registerCommand("statistic-reset",
1349 std::bind(&StatsMgr::statisticResetHandler, ph::_1, ph::_2));
1350
1351 CommandMgr::instance().registerCommand("statistic-remove",
1352 std::bind(&StatsMgr::statisticRemoveHandler, ph::_1, ph::_2));
1353
1354 CommandMgr::instance().registerCommand("statistic-get-all",
1355 std::bind(&StatsMgr::statisticGetAllHandler, ph::_1, ph::_2));
1356
1357 CommandMgr::instance().registerCommand("statistic-global-get-all",
1358 std::bind(&StatsMgr::statisticGlobalGetAllHandler, ph::_1, ph::_2));
1359
1360 CommandMgr::instance().registerCommand("statistic-reset-all",
1361 std::bind(&StatsMgr::statisticResetAllHandler, ph::_1, ph::_2));
1362
1363 CommandMgr::instance().registerCommand("statistic-remove-all",
1364 std::bind(&StatsMgr::statisticRemoveAllHandler, ph::_1, ph::_2));
1365
1366 CommandMgr::instance().registerCommand("statistic-sample-age-set",
1367 std::bind(&StatsMgr::statisticSetMaxSampleAgeHandler, ph::_1, ph::_2));
1368
1369 CommandMgr::instance().registerCommand("statistic-sample-age-set-all",
1370 std::bind(&ControlledDhcpv6Srv::commandStatisticSetMaxSampleAgeAllHandler, this, ph::_1, ph::_2));
1371
1372 CommandMgr::instance().registerCommand("statistic-sample-count-set",
1373 std::bind(&StatsMgr::statisticSetMaxSampleCountHandler, ph::_1, ph::_2));
1374
1375 CommandMgr::instance().registerCommand("statistic-sample-count-set-all",
1376 std::bind(&ControlledDhcpv6Srv::commandStatisticSetMaxSampleCountAllHandler, this, ph::_1, ph::_2));
1377}
1378
1380 setExitValue(exit_value);
1381 getIOService()->stop(); // Stop ASIO transmissions
1382 shutdown(); // Initiate DHCPv6 shutdown procedure.
1383}
1384
1386 try {
1387 MultiThreadingMgr::instance().apply(false, 0, 0);
1390
1391 // The closure captures either a shared pointer (memory leak)
1392 // or a raw pointer (pointing to a deleted object).
1396
1397 timer_mgr_->unregisterTimers();
1398
1399 cleanup();
1400
1401 // Close command sockets.
1404
1405 // Deregister any registered commands (please keep in alphabetic order)
1406 CommandMgr::instance().deregisterCommand("build-report");
1407 CommandMgr::instance().deregisterCommand("config-backend-pull");
1409 CommandMgr::instance().deregisterCommand("config-hash-get");
1410 CommandMgr::instance().deregisterCommand("config-reload");
1412 CommandMgr::instance().deregisterCommand("config-test");
1413 CommandMgr::instance().deregisterCommand("config-write");
1414 CommandMgr::instance().deregisterCommand("dhcp-disable");
1415 CommandMgr::instance().deregisterCommand("dhcp-enable");
1416 CommandMgr::instance().deregisterCommand("kea-lfc-start");
1417 CommandMgr::instance().deregisterCommand("leases-reclaim");
1418 CommandMgr::instance().deregisterCommand("subnet6-select-test");
1419 CommandMgr::instance().deregisterCommand("server-tag-get");
1421 CommandMgr::instance().deregisterCommand("statistic-get");
1422 CommandMgr::instance().deregisterCommand("statistic-get-all");
1423 CommandMgr::instance().deregisterCommand("statistic-global-get-all");
1424 CommandMgr::instance().deregisterCommand("statistic-remove");
1425 CommandMgr::instance().deregisterCommand("statistic-remove-all");
1426 CommandMgr::instance().deregisterCommand("statistic-reset");
1427 CommandMgr::instance().deregisterCommand("statistic-reset-all");
1428 CommandMgr::instance().deregisterCommand("statistic-sample-age-set");
1429 CommandMgr::instance().deregisterCommand("statistic-sample-age-set-all");
1430 CommandMgr::instance().deregisterCommand("statistic-sample-count-set");
1431 CommandMgr::instance().deregisterCommand("statistic-sample-count-set-all");
1433 CommandMgr::instance().deregisterCommand("version-get");
1434
1435 // Reset DatabaseConnection IO service.
1437 } catch (...) {
1438 // Don't want to throw exceptions from the destructor. The server
1439 // is shutting down anyway.
1440 }
1441
1442 server_ = NULL; // forget this instance. There should be no callback anymore
1443 // at this stage anyway.
1444}
1445
1446void
1447ControlledDhcpv6Srv::reclaimExpiredLeases(const size_t max_leases,
1448 const uint16_t timeout,
1449 const bool remove_lease,
1450 const uint16_t max_unwarned_cycles) {
1451 try {
1452 if (network_state_->isServiceEnabled()) {
1453 server_->alloc_engine_->reclaimExpiredLeases6(max_leases, timeout,
1454 remove_lease,
1455 max_unwarned_cycles);
1456 } else {
1458 .arg(CfgMgr::instance().getCurrentCfg()->
1459 getCfgExpiration()->getReclaimTimerWaitTime());
1460 }
1461 } catch (const std::exception& ex) {
1463 .arg(ex.what());
1464 }
1465 // We're using the ONE_SHOT timer so there is a need to re-schedule it.
1467}
1468
1469void
1470ControlledDhcpv6Srv::deleteExpiredReclaimedLeases(const uint32_t secs) {
1471 if (network_state_->isServiceEnabled()) {
1472 server_->alloc_engine_->deleteExpiredReclaimedLeases6(secs);
1473 }
1474
1475 // We're using the ONE_SHOT timer so there is a need to re-schedule it.
1477}
1478
1479bool
1480ControlledDhcpv6Srv::dbLostCallback(ReconnectCtlPtr db_reconnect_ctl) {
1481 if (!db_reconnect_ctl) {
1482 // This should never happen
1484 return (false);
1485 }
1486
1487 // Disable service until the connection is recovered.
1488 if (db_reconnect_ctl->retriesLeft() == db_reconnect_ctl->maxRetries() &&
1489 db_reconnect_ctl->alterServiceState()) {
1490 network_state_->disableService(NetworkState::DB_CONNECTION + db_reconnect_ctl->id());
1491 }
1492
1494 .arg(db_reconnect_ctl->id())
1495 .arg(db_reconnect_ctl->timerName());
1496
1497 // If reconnect isn't enabled log it, initiate a shutdown if needed and
1498 // return false.
1499 if (!db_reconnect_ctl->retriesLeft() ||
1500 !db_reconnect_ctl->retryInterval()) {
1502 .arg(db_reconnect_ctl->retriesLeft())
1503 .arg(db_reconnect_ctl->retryInterval())
1504 .arg(db_reconnect_ctl->id())
1505 .arg(db_reconnect_ctl->timerName());
1506 if (db_reconnect_ctl->exitOnFailure()) {
1507 shutdownServer(EXIT_FAILURE);
1508 }
1509 return (false);
1510 }
1511
1512 return (true);
1513}
1514
1515bool
1516ControlledDhcpv6Srv::dbRecoveredCallback(ReconnectCtlPtr db_reconnect_ctl) {
1517 if (!db_reconnect_ctl) {
1518 // This should never happen
1520 return (false);
1521 }
1522
1523 // Enable service after the connection is recovered.
1524 if (db_reconnect_ctl->retriesLeft() != db_reconnect_ctl->maxRetries() &&
1525 db_reconnect_ctl->alterServiceState()) {
1526 network_state_->enableService(NetworkState::DB_CONNECTION + db_reconnect_ctl->id());
1527 }
1528
1530 .arg(db_reconnect_ctl->id())
1531 .arg(db_reconnect_ctl->timerName());
1532
1533 db_reconnect_ctl->resetRetries();
1534
1535 return (true);
1536}
1537
1538bool
1539ControlledDhcpv6Srv::dbFailedCallback(ReconnectCtlPtr db_reconnect_ctl) {
1540 if (!db_reconnect_ctl) {
1541 // This should never happen
1543 return (false);
1544 }
1545
1547 .arg(db_reconnect_ctl->maxRetries())
1548 .arg(db_reconnect_ctl->id())
1549 .arg(db_reconnect_ctl->timerName());
1550
1551 if (db_reconnect_ctl->exitOnFailure()) {
1552 shutdownServer(EXIT_FAILURE);
1553 }
1554
1555 return (true);
1556}
1557
1558void
1559ControlledDhcpv6Srv::openSocketsFailedCallback(ReconnectCtlPtr reconnect_ctl) {
1560 if (!reconnect_ctl) {
1561 // This should never happen
1563 return;
1564 }
1565
1567 .arg(reconnect_ctl->maxRetries());
1568
1569 if (reconnect_ctl->exitOnFailure()) {
1570 shutdownServer(EXIT_FAILURE);
1571 }
1572}
1573
1574void
1575ControlledDhcpv6Srv::cbFetchUpdates(const SrvConfigPtr& srv_cfg,
1576 boost::shared_ptr<unsigned> failure_count) {
1577 // stop thread pool (if running)
1578 MultiThreadingCriticalSection cs;
1579
1580 try {
1581 // Fetch any configuration backend updates since our last fetch.
1582 server_->getCBControl()->databaseConfigFetch(srv_cfg,
1583 CBControlDHCPv6::FetchMode::FETCH_UPDATE);
1584 (*failure_count) = 0;
1585
1586 } catch (const std::exception& ex) {
1588 .arg(ex.what());
1589
1590 // We allow at most 10 consecutive failures after which we stop
1591 // making further attempts to fetch the configuration updates.
1592 // Let's return without re-scheduling the timer.
1593 if (++(*failure_count) > 10) {
1596 return;
1597 }
1598 }
1599
1600 // Reschedule the timer to fetch new updates or re-try if
1601 // the previous attempt resulted in an error.
1602 if (TimerMgr::instance()->isTimerRegistered("Dhcp6CBFetchTimer")) {
1603 TimerMgr::instance()->setup("Dhcp6CBFetchTimer");
1604 }
1605}
1606
1607} // namespace dhcp
1608} // namespace isc
CtrlAgentHooks Hooks
@ map
Definition data.h:147
@ integer
Definition data.h:140
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown if a function is called in a prohibited way.
virtual isc::data::ConstElementPtr processCommand(const isc::data::ConstElementPtr &cmd)
Triggers command processing.
void registerCommand(const std::string &cmd, CommandHandler handler)
Registers specified command handler for a given command.
static std::string getHash(const isc::data::ConstElementPtr &config)
returns a hash of a given Element structure
void deregisterCommand(const std::string &cmd)
Deregisters specified command handler.
static CommandMgr & instance()
CommandMgr is a singleton class.
static std::string DEFAULT_AUTHENTICATION_REALM
Default HTTP authentication realm.
static isc::asiolink::IOAddress DEFAULT_SOCKET_ADDRESS
Default socket address (127.0.0.1).
void closeCommandSockets()
Close http control sockets.
static HttpCommandMgr & instance()
HttpCommandMgr is a singleton class.
void setIOService(const asiolink::IOServicePtr &io_service)
Sets IO service to be used by the http command manager.
static UnixCommandMgr & instance()
UnixCommandMgr is a singleton class.
void setIOService(const asiolink::IOServicePtr &io_service)
Sets IO service to be used by the unix command manager.
void closeCommandSockets()
Shuts down any open unix control sockets.
static ElementPtr create(const Position &pos=ZERO_POSITION())
Definition data.cc:249
static ElementPtr createMap(const Position &pos=ZERO_POSITION())
Creates an empty MapElement type ElementPtr.
Definition data.cc:304
static ElementPtr createList(const Position &pos=ZERO_POSITION())
Creates an empty ListElement type ElementPtr.
Definition data.cc:299
static void setIOService(const isc::asiolink::IOServicePtr &io_service)
Sets IO service to be used by the database backends.
static DbCallback db_recovered_callback_
Optional callback function to invoke if an opened connection recovery succeeded.
static DbCallback db_failed_callback_
Optional callback function to invoke if an opened connection recovery failed.
static DbCallback db_lost_callback_
Optional callback function to invoke if an opened connection is lost.
void parse(std::string &access_string, isc::data::ConstElementPtr database_config)
Parse configuration value.
const DatabaseConnection::ParameterMap & getDbAccessParameters() const
Get database access parameters.
RAII class to enable DB reconnect retries on server startup.
static const std::string FLUSH_RECLAIMED_TIMER_NAME
Name of the timer for flushing reclaimed leases.
static const std::string RECLAIM_EXPIRED_TIMER_NAME
Name of the timer for reclaiming expired leases.
static OpenSocketsFailedCallback open_sockets_failed_callback_
Optional callback function to invoke if all retries of the opening sockets fail.
Definition cfg_iface.h:361
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition cfgmgr.cc:29
SrvConfigPtr getStagingCfg()
Returns a pointer to the staging configuration.
Definition cfgmgr.cc:121
void commit()
Commits the staging configuration.
Definition cfgmgr.cc:93
void clearStagingConfiguration()
Remove staging configuration.
Definition cfgmgr.cc:88
SrvConfigPtr getCurrentCfg()
Returns a pointer to the current configuration.
Definition cfgmgr.cc:116
static void apply(data::ConstElementPtr value)
apply multi threading configuration
void insert(const ClientClass &class_name)
Insert an element.
Definition classify.h:160
Controlled version of the DHCPv6 server.
void init(const std::string &config_file)
Initializes the server.
void cleanup()
Performs cleanup, immediately before termination.
static isc::data::ConstElementPtr finishConfigHookLibraries(isc::data::ConstElementPtr config)
Configuration checker for hook libraries.
virtual ~ControlledDhcpv6Srv()
Destructor.
static isc::data::ConstElementPtr processConfig(isc::data::ConstElementPtr config)
Configuration processor.
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.
isc::data::ConstElementPtr loadConfigFile(const std::string &file_name)
Configure DHCPv6 server using the configuration file specified.
static isc::data::ConstElementPtr checkConfig(isc::data::ConstElementPtr config)
Configuration checker.
ControlledDhcpv6Srv(uint16_t server_port=DHCP6_SERVER_PORT, uint16_t client_port=0)
Constructor.
virtual void open()
Open communication socket.
static Dhcp6to4Ipc & instance()
Returns pointer to the sole instance of Dhcp6to4Ipc.
void shutdown() override
Instructs the server to shut down.
Definition dhcp6_srv.cc:362
boost::shared_ptr< AllocEngine > alloc_engine_
Allocation Engine.
Definition dhcp6_srv.h:1245
uint16_t getServerPort() const
Get UDP port on which server should listen.
NetworkStatePtr & getNetworkState()
Returns pointer to the network state used by the server.
Definition dhcp6_srv.h:115
NetworkStatePtr network_state_
Holds information about disabled DHCP service and/or disabled subnet/network scopes.
Definition dhcp6_srv.h:1253
Dhcpv6Srv(uint16_t server_port=DHCP6_SERVER_PORT, uint16_t client_port=0)
Default constructor.
Definition dhcp6_srv.cc:263
static std::string getVersion(bool extended)
returns Kea version on stdout and exit.
asiolink::IOServicePtr & getIOService()
Returns pointer to the IO service used by the server.
Definition dhcp6_srv.h:110
void startD2()
Starts DHCP_DDNS client IO if DDNS updates are enabled.
static void create()
Creates new instance of the HostMgr.
Definition host_mgr.cc:52
static IfaceMgr & instance()
IfaceMgr is a singleton class.
Definition iface_mgr.cc:54
static TrackingLeaseMgr & instance()
Return current lease manager.
static void destroy()
Destroy lease manager.
static bool haveInstance()
Indicates if the lease manager has been instantiated.
virtual data::ElementPtr getStatus() const
Return status information.
static void commitRuntimeOptionDefs()
Commits runtime option definitions.
Definition libdhcp++.cc:248
static bool isLFCProcessRunning(const std::string file_name, Universe u)
Check if LFC is running.
static const unsigned int DB_CONNECTION
The network state is being altered by the DB connection recovery mechanics.
static const unsigned int USER_COMMAND
Origin of the network state transition.
static const unsigned int HA_REMOTE_COMMAND
The network state is being altered by a "dhcp-disable" or "dhcp-enable" command sent by a HA partner.
Evaluation context, an interface to the expression evaluation.
isc::data::ElementPtr parseFile(const std::string &filename, ParserType parser_type)
Run the parser on the file specified.
@ PARSER_DHCP6
This parser will parse the content as Dhcp6 config wrapped in a map (that's the regular config file)
Manages a pool of asynchronous interval timers.
Definition timer_mgr.h:62
static const TimerMgrPtr & instance()
Returns pointer to the sole instance of the TimerMgr.
Definition timer_mgr.cc:446
@ NEXT_STEP_DROP
drop the packet
static int registerHook(const std::string &name)
Register Hook.
static bool calloutsPresent(int index)
Are callouts present?
static boost::shared_ptr< CalloutHandle > createCalloutHandle()
Return callout handle.
static void callCallouts(int index, CalloutHandle &handle)
Calls the callouts for a given hook.
std::string getConfigFile() const
Returns config file name.
Definition daemon.cc:105
virtual size_t writeConfigFile(const std::string &config_file, isc::data::ConstElementPtr cfg=isc::data::ConstElementPtr()) const
Writes current configuration to specified file.
Definition daemon.cc:267
isc::asiolink::IOSignalSetPtr signal_set_
A pointer to the object installing custom signal handlers.
Definition daemon.h:272
boost::posix_time::ptime start_
Timestamp of the start of the daemon.
Definition daemon.h:278
void checkWriteConfigFile(std::string &file)
Checks the to-be-written configuration file name.
Definition daemon.cc:130
void setExitValue(int value)
Sets the exit value.
Definition daemon.h:242
isc::data::ConstElementPtr redactConfig(isc::data::ConstElementPtr const &config)
Redact a configuration.
Definition daemon.cc:295
static StatsMgr & instance()
Statistics Manager accessor method.
static MultiThreadingMgr & instance()
Returns a single instance of Multi Threading Manager.
void apply(bool enabled, uint32_t thread_count, uint32_t queue_size)
Apply the multi-threading related settings.
This file contains several functions and constants that are used for handling commands and responses ...
@ D6O_INTERFACE_ID
Definition dhcp6.h:38
@ D6O_SERVERID
Definition dhcp6.h:22
Defines the Dhcp6to4Ipc class.
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
isc::data::ConstElementPtr statisticSetMaxSampleCountAllHandler(const isc::data::ConstElementPtr &params)
Handles statistic-sample-count-set-all command.
static isc::data::ConstElementPtr statisticResetHandler(const std::string &name, const isc::data::ConstElementPtr &params)
Handles statistic-reset command.
static isc::data::ConstElementPtr statisticGetAllHandler(const std::string &name, const isc::data::ConstElementPtr &params)
Handles statistic-get-all command.
static isc::data::ConstElementPtr statisticRemoveHandler(const std::string &name, const isc::data::ConstElementPtr &params)
Handles statistic-remove command.
static isc::data::ConstElementPtr statisticGetHandler(const std::string &name, const isc::data::ConstElementPtr &params)
Handles statistic-get command.
static isc::data::ConstElementPtr statisticGlobalGetAllHandler(const std::string &name, const isc::data::ConstElementPtr &params)
Handles statistic-global-get-all command.
isc::data::ConstElementPtr statisticSetMaxSampleAgeAllHandler(const isc::data::ConstElementPtr &params)
Handles statistic-sample-age-set-all command.
static isc::data::ConstElementPtr statisticResetAllHandler(const std::string &name, const isc::data::ConstElementPtr &params)
Handles statistic-reset-all command.
static isc::data::ConstElementPtr statisticSetMaxSampleAgeHandler(const std::string &name, const isc::data::ConstElementPtr &params)
Handles statistic-sample-age-set command.
static isc::data::ConstElementPtr statisticRemoveAllHandler(const std::string &name, const isc::data::ConstElementPtr &params)
Handles statistic-remove-all command.
static isc::data::ConstElementPtr statisticSetMaxSampleCountHandler(const std::string &name, const isc::data::ConstElementPtr &params)
Handles statistic-sample-count-set command.
uint32_t getMaxSampleCountDefault() const
Get default count limit.
const StatsDuration & getMaxSampleAgeDefault() const
Get default duration limit.
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition macros.h:32
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition macros.h:20
#define LOG_WARN(LOGGER, MESSAGE)
Macro to conveniently test warn output and log it.
Definition macros.h:26
#define LOG_FATAL(LOGGER, MESSAGE)
Macro to conveniently test fatal output and log it.
Definition macros.h:38
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition macros.h:14
const int CONTROL_RESULT_EMPTY
Status code indicating that the specified command was completed correctly, but failed to produce any ...
ConstElementPtr parseAnswer(int &rcode, const ConstElementPtr &msg)
Parses a standard config/command level answer and returns arguments or text status code.
ConstElementPtr createCommand(const std::string &command)
Creates a standard command message with no argument (of the form { "command": "my_command" }...
const int CONTROL_RESULT_ERROR
Status code indicating a general failure.
ConstElementPtr createAnswer(const int status_code, const std::string &text, const ConstElementPtr &arg)
Creates a standard config/command level answer message.
ConstElementPtr createAnswer()
Creates a standard config/command level success answer message (i.e.
const int CONTROL_RESULT_COMMAND_UNSUPPORTED
Status code indicating that the specified command is not supported.
const int CONTROL_RESULT_SUCCESS
Status code indicating a successful operation.
boost::shared_ptr< const Element > ConstElementPtr
Definition data.h:29
boost::shared_ptr< Element > ElementPtr
Definition data.h:28
@ error
Definition db_log.h:118
std::string getConfigReport()
Definition cfgrpt.cc:20
const isc::log::MessageID DHCP6_DB_RECONNECT_NO_DB_CTL
const isc::log::MessageID DHCP6_OPEN_SOCKETS_NO_RECONNECT_CTL
const isc::log::MessageID DHCP6_USING_SERVERID
const isc::log::MessageID DHCP6_CONFIG_LOAD_FAIL
boost::shared_ptr< const Subnet6 > ConstSubnet6Ptr
A const pointer to a Subnet6 object.
Definition subnet.h:623
const isc::log::MessageID DHCP6_DB_RECONNECT_SUCCEEDED
isc::data::ConstElementPtr configureDhcp6Server(Dhcpv6Srv &server, isc::data::ConstElementPtr config_set, bool check_only, bool extra_checks)
Configure DHCPv6 server (Dhcpv6Srv) with a set of configuration values.
const isc::log::MessageID DHCP6_RECLAIM_EXPIRED_LEASES_SKIPPED
boost::shared_ptr< CfgDbAccess > CfgDbAccessPtr
A pointer to the CfgDbAccess.
boost::shared_ptr< Iface > IfacePtr
Type definition for the pointer to an Iface object.
Definition iface_mgr.h:487
boost::shared_ptr< DUID > DuidPtr
Definition duid.h:136
const int DBG_DHCP6_COMMAND
Debug level used to log receiving commands.
Definition dhcp6_log.h:28
const isc::log::MessageID DHCP6_CB_PERIODIC_FETCH_UPDATES_FAIL
const isc::log::MessageID DHCP6_RECLAIM_EXPIRED_LEASES_FAIL
const isc::log::MessageID DHCP6_OPEN_SOCKETS_FAILED
boost::shared_ptr< SrvConfig > SrvConfigPtr
Non-const pointer to the SrvConfig.
const isc::log::MessageID DHCP6_DYNAMIC_RECONFIGURATION_SUCCESS
const isc::log::MessageID DHCP6_CB_ON_DEMAND_FETCH_UPDATES_FAIL
const isc::log::MessageID DHCP6_CB_PERIODIC_FETCH_UPDATES_RETRIES_EXHAUSTED
const isc::log::MessageID DHCP6_NOT_RUNNING
boost::shared_ptr< SharedNetwork6 > SharedNetwork6Ptr
Pointer to SharedNetwork6 object.
const isc::log::MessageID DHCP6_DYNAMIC_RECONFIGURATION_FAIL
const isc::log::MessageID DHCP6_CONFIG_UNSUPPORTED_OBJECT
const isc::log::MessageID DHCP6_CONFIG_UNRECOVERABLE_ERROR
const isc::log::MessageID DHCP6_CONFIG_RECEIVED
const isc::log::MessageID DHCP6_DB_RECONNECT_DISABLED
const isc::log::MessageID DHCP6_DYNAMIC_RECONFIGURATION
const isc::log::MessageID DHCP6_DB_RECONNECT_LOST_CONNECTION
const int DBG_DHCP6_BASIC
Debug level used to trace basic operations within the code.
Definition dhcp6_log.h:31
isc::log::Logger dhcp6_logger(DHCP6_APP_LOGGER_NAME)
Base logger for DHCPv6 server.
Definition dhcp6_log.h:88
const isc::log::MessageID DHCP6_MULTI_THREADING_INFO
const isc::log::MessageID DHCP6_DB_RECONNECT_FAILED
boost::shared_ptr< Option > OptionPtr
Definition option.h:37
const isc::log::MessageID DHCP6_CONFIG_PACKET_QUEUE
boost::shared_ptr< CalloutHandle > CalloutHandlePtr
A shared pointer to a CalloutHandle object.
long toSeconds(const StatsDuration &dur)
Returns the number of seconds in a duration.
Definition observation.h:49
void decodeFormattedHexString(const string &hex_string, vector< uint8_t > &binary)
Converts a formatted string of hexadecimal digits into a vector.
Definition str.cc:212
vector< uint8_t > quotedStringToBinary(const string &quoted_string)
Converts a string in quotes into vector.
Definition str.cc:139
boost::shared_ptr< ReconnectCtl > ReconnectCtlPtr
Pointer to an instance of ReconnectCtl.
Defines the logger used by the top-level component of kea-lfc.
std::string iface_name_
Name of the interface on which the message was received.
ClientClasses client_classes_
Classes that the client belongs to.
asiolink::IOAddress remote_address_
Source address of the message.
OptionPtr interface_id_
Interface id option.
asiolink::IOAddress first_relay_linkaddr_
First relay link address.