Kea 3.1.1
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 status->set("extended-info-tables", Element::create(
926 CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getExtendedInfoTablesEnabled()));
927
928 // Iterate through the interfaces and get all the errors.
929 ElementPtr socket_errors(Element::createList());
930 for (IfacePtr const& interface : IfaceMgr::instance().getIfaces()) {
931 for (std::string const& error : interface->getErrors()) {
932 socket_errors->add(Element::create(error));
933 }
934 }
935
936 // Abstract the information from all sockets into a single status.
938 if (socket_errors->empty()) {
939 sockets->set("status", Element::create("ready"));
940 } else {
941 ReconnectCtlPtr const reconnect_ctl(
942 CfgMgr::instance().getCurrentCfg()->getCfgIface()->getReconnectCtl());
943 if (reconnect_ctl && reconnect_ctl->retriesLeft()) {
944 sockets->set("status", Element::create("retrying"));
945 } else {
946 sockets->set("status", Element::create("failed"));
947 }
948 sockets->set("errors", socket_errors);
949 }
950 status->set("sockets", sockets);
951
952 status->set("dhcp-state", network_state_->toElement());
953
954 return (createAnswer(CONTROL_RESULT_SUCCESS, status));
955}
956
958ControlledDhcpv6Srv::commandStatisticSetMaxSampleCountAllHandler(const string&,
959 ConstElementPtr args) {
960 StatsMgr& stats_mgr = StatsMgr::instance();
962 // Update the default parameter.
963 long max_samples = stats_mgr.getMaxSampleCountDefault();
964 CfgMgr::instance().getCurrentCfg()->addConfiguredGlobal(
965 "statistic-default-sample-count", Element::create(max_samples));
966 return (answer);
967}
968
970ControlledDhcpv6Srv::commandStatisticSetMaxSampleAgeAllHandler(const string&,
971 ConstElementPtr args) {
972 StatsMgr& stats_mgr = StatsMgr::instance();
974 // Update the default parameter.
975 auto duration = stats_mgr.getMaxSampleAgeDefault();
976 long max_age = toSeconds(duration);
977 CfgMgr::instance().getCurrentCfg()->addConfiguredGlobal(
978 "statistic-default-sample-age", Element::create(max_age));
979 return (answer);
980}
981
985
986 // Allow DB reconnect on startup. The database connection parameters specify
987 // respective details.
989
990 // Single stream instance used in all error clauses
991 std::ostringstream err;
992
993 if (!srv) {
994 err << "Server object not initialized, can't process config.";
996 }
997
999 .arg(srv->redactConfig(config)->str());
1000
1001 // Destroy lease manager before hooks unload.
1003
1004 // Destroy host manager before hooks unload.
1006
1008
1009 // Check that configuration was successful. If not, do not reopen sockets
1010 // and don't bother with DDNS stuff.
1011 try {
1012 int rcode = 0;
1013 isc::config::parseAnswer(rcode, answer);
1014 if (rcode != 0) {
1015 return (answer);
1016 }
1017 } catch (const std::exception& ex) {
1018 err << "Failed to process configuration:" << ex.what();
1020 }
1021
1022 // Re-open lease and host database with new parameters.
1023 try {
1025 std::bind(&ControlledDhcpv6Srv::dbLostCallback, srv, ph::_1);
1026
1028 std::bind(&ControlledDhcpv6Srv::dbRecoveredCallback, srv, ph::_1);
1029
1031 std::bind(&ControlledDhcpv6Srv::dbFailedCallback, srv, ph::_1);
1032
1033 CfgDbAccessPtr cfg_db = CfgMgr::instance().getStagingCfg()->getCfgDbAccess();
1034 string params = "universe=6";
1035 if (cfg_db->getExtendedInfoTablesEnabled()) {
1036 params += " extended-info-tables=true";
1037 }
1038 cfg_db->setAppendedParameters(params);
1039 cfg_db->createManagers();
1040 // Reset counters related to connections as all managers have been recreated.
1041 srv->getNetworkState()->resetForDbConnection();
1042 srv->getNetworkState()->resetForLocalCommands();
1043 srv->getNetworkState()->resetForRemoteCommands();
1044 } catch (const std::exception& ex) {
1045 err << "Unable to open database: " << ex.what();
1047 }
1048
1049 // Regenerate server identifier if needed.
1050 try {
1051 const std::string duid_file =
1052 std::string(CfgMgr::instance().getDataDir()) + "/" +
1053 std::string(SERVER_DUID_FILE);
1054 DuidPtr duid = CfgMgr::instance().getStagingCfg()->getCfgDUID()->create(duid_file);
1055 server_->serverid_.reset(new Option(Option::V6, D6O_SERVERID, duid->getDuid()));
1056 if (duid) {
1058 .arg(duid->toText())
1059 .arg(duid_file);
1060 }
1061
1062 } catch (const std::exception& ex) {
1063 err << "unable to configure server identifier: " << ex.what();
1065 }
1066
1067 // Server will start DDNS communications if its enabled.
1068 try {
1069 srv->startD2();
1070 } catch (const std::exception& ex) {
1071 err << "Error starting DHCP_DDNS client after server reconfiguration: "
1072 << ex.what();
1074 }
1075
1076 // Setup DHCPv4-over-DHCPv6 IPC
1077 try {
1079 } catch (const std::exception& ex) {
1080 err << "error starting DHCPv4-over-DHCPv6 IPC "
1081 " after server reconfiguration: " << ex.what();
1083 }
1084
1085 // Configure DHCP packet queueing
1086 try {
1088 qc = CfgMgr::instance().getStagingCfg()->getDHCPQueueControl();
1089 if (IfaceMgr::instance().configureDHCPPacketQueue(AF_INET6, qc)) {
1091 .arg(IfaceMgr::instance().getPacketQueue6()->getInfoStr());
1092 }
1093
1094 } catch (const std::exception& ex) {
1095 err << "Error setting packet queue controls after server reconfiguration: "
1096 << ex.what();
1098 }
1099
1100 // Configure a callback to shut down the server when the bind socket
1101 // attempts exceeded.
1103 std::bind(&ControlledDhcpv6Srv::openSocketsFailedCallback, srv, ph::_1);
1104
1105 // Configuration may change active interfaces. Therefore, we have to reopen
1106 // sockets according to new configuration. It is possible that this
1107 // operation will fail for some interfaces but the openSockets function
1108 // guards against exceptions and invokes a callback function to
1109 // log warnings. Since we allow that this fails for some interfaces there
1110 // is no need to rollback configuration if socket fails to open on any
1111 // of the interfaces.
1112 CfgMgr::instance().getStagingCfg()->getCfgIface()->
1113 openSockets(AF_INET6, srv->getServerPort());
1114
1115 // Install the timers for handling leases reclamation.
1116 try {
1117 CfgMgr::instance().getStagingCfg()->getCfgExpiration()->
1118 setupTimers(&ControlledDhcpv6Srv::reclaimExpiredLeases,
1119 &ControlledDhcpv6Srv::deleteExpiredReclaimedLeases,
1120 server_);
1121
1122 } catch (const std::exception& ex) {
1123 err << "unable to setup timers for periodically running the"
1124 " reclamation of the expired leases: "
1125 << ex.what() << ".";
1127 }
1128
1129 // Setup config backend polling, if configured for it.
1130 auto ctl_info = CfgMgr::instance().getStagingCfg()->getConfigControlInfo();
1131 if (ctl_info) {
1132 long fetch_time = static_cast<long>(ctl_info->getConfigFetchWaitTime());
1133 // Only schedule the CB fetch timer if the fetch wait time is greater
1134 // than 0.
1135 if (fetch_time > 0) {
1136 // When we run unit tests, we want to use milliseconds unit for the
1137 // specified interval. Otherwise, we use seconds. Note that using
1138 // milliseconds as a unit in unit tests prevents us from waiting 1
1139 // second on more before the timer goes off. Instead, we wait one
1140 // millisecond which significantly reduces the test time.
1141 if (!server_->inTestMode()) {
1142 fetch_time = 1000 * fetch_time;
1143 }
1144
1145 boost::shared_ptr<unsigned> failure_count(new unsigned(0));
1147 registerTimer("Dhcp6CBFetchTimer",
1148 std::bind(&ControlledDhcpv6Srv::cbFetchUpdates,
1149 server_, CfgMgr::instance().getStagingCfg(),
1150 failure_count),
1151 fetch_time,
1153 TimerMgr::instance()->setup("Dhcp6CBFetchTimer");
1154 }
1155 }
1156
1157 // Finally, we can commit runtime option definitions in libdhcp++. This is
1158 // exception free.
1160
1162 if (notify_libraries) {
1163 return (notify_libraries);
1164 }
1165
1166 // Initialize the allocators. If the user selected a Free Lease Queue Allocator
1167 // for any of the subnets, the server will now populate free leases to the queue.
1168 // It may take a while!
1169 try {
1170 CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->initAllocatorsAfterConfigure();
1171
1172 } catch (const std::exception& ex) {
1173 err << "Error initializing the lease allocators: "
1174 << ex.what();
1176 }
1177
1178 // Apply multi threading settings.
1179 // @note These settings are applied/updated only if no errors occur while
1180 // applying the new configuration.
1181 // @todo This should be fixed.
1182 try {
1183 CfgMultiThreading::apply(CfgMgr::instance().getStagingCfg()->getDHCPMultiThreading());
1184 } catch (const std::exception& ex) {
1185 err << "Error applying multi threading settings: "
1186 << ex.what();
1188 }
1189
1190 return (answer);
1191}
1192
1196 // This hook point notifies hooks libraries that the configuration of the
1197 // DHCPv6 server has completed. It provides the hook library with the pointer
1198 // to the common IO service object, new server configuration in the JSON
1199 // format and with the pointer to the configuration storage where the
1200 // parsed configuration is stored.
1201 if (HooksManager::calloutsPresent(Hooks.hooks_index_dhcp6_srv_configured_)) {
1203
1204 callout_handle->setArgument("io_context", srv->getIOService());
1205 callout_handle->setArgument("network_state", srv->getNetworkState());
1206 callout_handle->setArgument("json_config", config);
1207 callout_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
1208
1209 HooksManager::callCallouts(Hooks.hooks_index_dhcp6_srv_configured_,
1210 *callout_handle);
1211
1212 // If next step is DROP, report a configuration error.
1213 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1214 string error;
1215 try {
1216 callout_handle->getArgument("error", error);
1217 } catch (NoSuchArgument const& ex) {
1218 error = "unknown error";
1219 }
1221 }
1222 }
1223
1224 return (ConstElementPtr());
1225}
1226
1230
1231 if (!srv) {
1233 "Server object not initialized, can't process config.");
1234 return (no_srv);
1235 }
1236
1238 .arg(srv->redactConfig(config)->str());
1239
1240 return (configureDhcp6Server(*srv, config, true));
1241}
1242
1243ControlledDhcpv6Srv::ControlledDhcpv6Srv(uint16_t server_port /*= DHCP6_SERVER_PORT*/,
1244 uint16_t client_port /*= 0*/)
1245 : Dhcpv6Srv(server_port, client_port), timer_mgr_(TimerMgr::instance()) {
1246 if (getInstance()) {
1248 "There is another Dhcpv6Srv instance already.");
1249 }
1250 server_ = this; // remember this instance for later use in handlers
1251
1252 // ProcessSpawn uses IO service to handle signal set events.
1254
1255 // TimerMgr uses IO service to run asynchronous timers.
1256 TimerMgr::instance()->setIOService(getIOService());
1257
1258 // Command managers use IO service to run asynchronous socket operations.
1261
1262 // Set the HTTP default socket address to the IPv6 (vs IPv4) loopback.
1264
1265 // Set the HTTP authentication default realm.
1267
1268 // DatabaseConnection uses IO service to run asynchronous timers.
1270
1271 // These are the commands always supported by the DHCPv6 server.
1272 // Please keep the list in alphabetic order.
1273 CommandMgr::instance().registerCommand("build-report",
1274 std::bind(&ControlledDhcpv6Srv::commandBuildReportHandler, this, ph::_1, ph::_2));
1275
1276 CommandMgr::instance().registerCommand("config-backend-pull",
1277 std::bind(&ControlledDhcpv6Srv::commandConfigBackendPullHandler, this, ph::_1, ph::_2));
1278
1280 std::bind(&ControlledDhcpv6Srv::commandConfigGetHandler, this, ph::_1, ph::_2));
1281
1282 CommandMgr::instance().registerCommand("config-hash-get",
1283 std::bind(&ControlledDhcpv6Srv::commandConfigHashGetHandler, this, ph::_1, ph::_2));
1284
1285 CommandMgr::instance().registerCommand("config-reload",
1286 std::bind(&ControlledDhcpv6Srv::commandConfigReloadHandler, this, ph::_1, ph::_2));
1287
1289 std::bind(&ControlledDhcpv6Srv::commandConfigSetHandler, this, ph::_1, ph::_2));
1290
1291 CommandMgr::instance().registerCommand("config-test",
1292 std::bind(&ControlledDhcpv6Srv::commandConfigTestHandler, this, ph::_1, ph::_2));
1293
1294 CommandMgr::instance().registerCommand("config-write",
1295 std::bind(&ControlledDhcpv6Srv::commandConfigWriteHandler, this, ph::_1, ph::_2));
1296
1297 CommandMgr::instance().registerCommand("dhcp-enable",
1298 std::bind(&ControlledDhcpv6Srv::commandDhcpEnableHandler, this, ph::_1, ph::_2));
1299
1300 CommandMgr::instance().registerCommand("dhcp-disable",
1301 std::bind(&ControlledDhcpv6Srv::commandDhcpDisableHandler, this, ph::_1, ph::_2));
1302
1303 CommandMgr::instance().registerCommand("leases-reclaim",
1304 std::bind(&ControlledDhcpv6Srv::commandLeasesReclaimHandler, this, ph::_1, ph::_2));
1305
1306 CommandMgr::instance().registerCommand("subnet6-select-test",
1307 std::bind(&ControlledDhcpv6Srv::commandSubnet6SelectTestHandler, this, ph::_1, ph::_2));
1308
1309 CommandMgr::instance().registerCommand("server-tag-get",
1310 std::bind(&ControlledDhcpv6Srv::commandServerTagGetHandler, this, ph::_1, ph::_2));
1311
1313 std::bind(&ControlledDhcpv6Srv::commandShutdownHandler, this, ph::_1, ph::_2));
1314
1316 std::bind(&ControlledDhcpv6Srv::commandStatusGetHandler, this, ph::_1, ph::_2));
1317
1318 CommandMgr::instance().registerCommand("version-get",
1319 std::bind(&ControlledDhcpv6Srv::commandVersionGetHandler, this, ph::_1, ph::_2));
1320
1321 // Register statistic related commands
1322 CommandMgr::instance().registerCommand("statistic-get",
1323 std::bind(&StatsMgr::statisticGetHandler, ph::_1, ph::_2));
1324
1325 CommandMgr::instance().registerCommand("statistic-reset",
1326 std::bind(&StatsMgr::statisticResetHandler, ph::_1, ph::_2));
1327
1328 CommandMgr::instance().registerCommand("statistic-remove",
1329 std::bind(&StatsMgr::statisticRemoveHandler, ph::_1, ph::_2));
1330
1331 CommandMgr::instance().registerCommand("statistic-get-all",
1332 std::bind(&StatsMgr::statisticGetAllHandler, ph::_1, ph::_2));
1333
1334 CommandMgr::instance().registerCommand("statistic-reset-all",
1335 std::bind(&StatsMgr::statisticResetAllHandler, ph::_1, ph::_2));
1336
1337 CommandMgr::instance().registerCommand("statistic-remove-all",
1338 std::bind(&StatsMgr::statisticRemoveAllHandler, ph::_1, ph::_2));
1339
1340 CommandMgr::instance().registerCommand("statistic-sample-age-set",
1341 std::bind(&StatsMgr::statisticSetMaxSampleAgeHandler, ph::_1, ph::_2));
1342
1343 CommandMgr::instance().registerCommand("statistic-sample-age-set-all",
1344 std::bind(&ControlledDhcpv6Srv::commandStatisticSetMaxSampleAgeAllHandler, this, ph::_1, ph::_2));
1345
1346 CommandMgr::instance().registerCommand("statistic-sample-count-set",
1347 std::bind(&StatsMgr::statisticSetMaxSampleCountHandler, ph::_1, ph::_2));
1348
1349 CommandMgr::instance().registerCommand("statistic-sample-count-set-all",
1350 std::bind(&ControlledDhcpv6Srv::commandStatisticSetMaxSampleCountAllHandler, this, ph::_1, ph::_2));
1351}
1352
1354 setExitValue(exit_value);
1355 getIOService()->stop(); // Stop ASIO transmissions
1356 shutdown(); // Initiate DHCPv6 shutdown procedure.
1357}
1358
1360 try {
1361 MultiThreadingMgr::instance().apply(false, 0, 0);
1364
1365 // The closure captures either a shared pointer (memory leak)
1366 // or a raw pointer (pointing to a deleted object).
1370
1371 timer_mgr_->unregisterTimers();
1372
1373 cleanup();
1374
1375 // Close command sockets.
1378
1379 // Deregister any registered commands (please keep in alphabetic order)
1380 CommandMgr::instance().deregisterCommand("build-report");
1381 CommandMgr::instance().deregisterCommand("config-backend-pull");
1383 CommandMgr::instance().deregisterCommand("config-hash-get");
1384 CommandMgr::instance().deregisterCommand("config-reload");
1386 CommandMgr::instance().deregisterCommand("config-test");
1387 CommandMgr::instance().deregisterCommand("config-write");
1388 CommandMgr::instance().deregisterCommand("dhcp-disable");
1389 CommandMgr::instance().deregisterCommand("dhcp-enable");
1390 CommandMgr::instance().deregisterCommand("leases-reclaim");
1391 CommandMgr::instance().deregisterCommand("subnet6-select-test");
1392 CommandMgr::instance().deregisterCommand("server-tag-get");
1394 CommandMgr::instance().deregisterCommand("statistic-get");
1395 CommandMgr::instance().deregisterCommand("statistic-get-all");
1396 CommandMgr::instance().deregisterCommand("statistic-remove");
1397 CommandMgr::instance().deregisterCommand("statistic-remove-all");
1398 CommandMgr::instance().deregisterCommand("statistic-reset");
1399 CommandMgr::instance().deregisterCommand("statistic-reset-all");
1400 CommandMgr::instance().deregisterCommand("statistic-sample-age-set");
1401 CommandMgr::instance().deregisterCommand("statistic-sample-age-set-all");
1402 CommandMgr::instance().deregisterCommand("statistic-sample-count-set");
1403 CommandMgr::instance().deregisterCommand("statistic-sample-count-set-all");
1405 CommandMgr::instance().deregisterCommand("version-get");
1406
1407 // Reset DatabaseConnection IO service.
1409 } catch (...) {
1410 // Don't want to throw exceptions from the destructor. The server
1411 // is shutting down anyway.
1412 }
1413
1414 server_ = NULL; // forget this instance. There should be no callback anymore
1415 // at this stage anyway.
1416}
1417
1418void
1419ControlledDhcpv6Srv::reclaimExpiredLeases(const size_t max_leases,
1420 const uint16_t timeout,
1421 const bool remove_lease,
1422 const uint16_t max_unwarned_cycles) {
1423 try {
1424 if (network_state_->isServiceEnabled()) {
1425 server_->alloc_engine_->reclaimExpiredLeases6(max_leases, timeout,
1426 remove_lease,
1427 max_unwarned_cycles);
1428 } else {
1430 .arg(CfgMgr::instance().getCurrentCfg()->
1431 getCfgExpiration()->getReclaimTimerWaitTime());
1432 }
1433 } catch (const std::exception& ex) {
1435 .arg(ex.what());
1436 }
1437 // We're using the ONE_SHOT timer so there is a need to re-schedule it.
1439}
1440
1441void
1442ControlledDhcpv6Srv::deleteExpiredReclaimedLeases(const uint32_t secs) {
1443 if (network_state_->isServiceEnabled()) {
1444 server_->alloc_engine_->deleteExpiredReclaimedLeases6(secs);
1445 }
1446
1447 // We're using the ONE_SHOT timer so there is a need to re-schedule it.
1449}
1450
1451bool
1452ControlledDhcpv6Srv::dbLostCallback(ReconnectCtlPtr db_reconnect_ctl) {
1453 if (!db_reconnect_ctl) {
1454 // This should never happen
1456 return (false);
1457 }
1458
1459 // Disable service until the connection is recovered.
1460 if (db_reconnect_ctl->retriesLeft() == db_reconnect_ctl->maxRetries() &&
1461 db_reconnect_ctl->alterServiceState()) {
1462 network_state_->disableService(NetworkState::DB_CONNECTION + db_reconnect_ctl->id());
1463 }
1464
1466 .arg(db_reconnect_ctl->id())
1467 .arg(db_reconnect_ctl->timerName());
1468
1469 // If reconnect isn't enabled log it, initiate a shutdown if needed and
1470 // return false.
1471 if (!db_reconnect_ctl->retriesLeft() ||
1472 !db_reconnect_ctl->retryInterval()) {
1474 .arg(db_reconnect_ctl->retriesLeft())
1475 .arg(db_reconnect_ctl->retryInterval())
1476 .arg(db_reconnect_ctl->id())
1477 .arg(db_reconnect_ctl->timerName());
1478 if (db_reconnect_ctl->exitOnFailure()) {
1479 shutdownServer(EXIT_FAILURE);
1480 }
1481 return (false);
1482 }
1483
1484 return (true);
1485}
1486
1487bool
1488ControlledDhcpv6Srv::dbRecoveredCallback(ReconnectCtlPtr db_reconnect_ctl) {
1489 if (!db_reconnect_ctl) {
1490 // This should never happen
1492 return (false);
1493 }
1494
1495 // Enable service after the connection is recovered.
1496 if (db_reconnect_ctl->retriesLeft() != db_reconnect_ctl->maxRetries() &&
1497 db_reconnect_ctl->alterServiceState()) {
1498 network_state_->enableService(NetworkState::DB_CONNECTION + db_reconnect_ctl->id());
1499 }
1500
1502 .arg(db_reconnect_ctl->id())
1503 .arg(db_reconnect_ctl->timerName());
1504
1505 db_reconnect_ctl->resetRetries();
1506
1507 return (true);
1508}
1509
1510bool
1511ControlledDhcpv6Srv::dbFailedCallback(ReconnectCtlPtr db_reconnect_ctl) {
1512 if (!db_reconnect_ctl) {
1513 // This should never happen
1515 return (false);
1516 }
1517
1519 .arg(db_reconnect_ctl->maxRetries())
1520 .arg(db_reconnect_ctl->id())
1521 .arg(db_reconnect_ctl->timerName());
1522
1523 if (db_reconnect_ctl->exitOnFailure()) {
1524 shutdownServer(EXIT_FAILURE);
1525 }
1526
1527 return (true);
1528}
1529
1530void
1531ControlledDhcpv6Srv::openSocketsFailedCallback(ReconnectCtlPtr reconnect_ctl) {
1532 if (!reconnect_ctl) {
1533 // This should never happen
1535 return;
1536 }
1537
1539 .arg(reconnect_ctl->maxRetries());
1540
1541 if (reconnect_ctl->exitOnFailure()) {
1542 shutdownServer(EXIT_FAILURE);
1543 }
1544}
1545
1546void
1547ControlledDhcpv6Srv::cbFetchUpdates(const SrvConfigPtr& srv_cfg,
1548 boost::shared_ptr<unsigned> failure_count) {
1549 // stop thread pool (if running)
1550 MultiThreadingCriticalSection cs;
1551
1552 try {
1553 // Fetch any configuration backend updates since our last fetch.
1554 server_->getCBControl()->databaseConfigFetch(srv_cfg,
1555 CBControlDHCPv6::FetchMode::FETCH_UPDATE);
1556 (*failure_count) = 0;
1557
1558 } catch (const std::exception& ex) {
1560 .arg(ex.what());
1561
1562 // We allow at most 10 consecutive failures after which we stop
1563 // making further attempts to fetch the configuration updates.
1564 // Let's return without re-scheduling the timer.
1565 if (++(*failure_count) > 10) {
1568 return;
1569 }
1570 }
1571
1572 // Reschedule the timer to fetch new updates or re-try if
1573 // the previous attempt resulted in an error.
1574 if (TimerMgr::instance()->isTimerRegistered("Dhcp6CBFetchTimer")) {
1575 TimerMgr::instance()->setup("Dhcp6CBFetchTimer");
1576 }
1577}
1578
1579} // namespace dhcp
1580} // 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:361
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:262
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 void destroy()
Destroy lease manager.
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:104
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:250
isc::asiolink::IOSignalSetPtr signal_set_
A pointer to the object installing custom signal handlers.
Definition daemon.h:266
boost::posix_time::ptime start_
Timestamp of the start of the daemon.
Definition daemon.h:272
void checkWriteConfigFile(std::string &file)
Checks the to-be-written configuration file name.
Definition daemon.cc:129
void setExitValue(int value)
Sets the exit value.
Definition daemon.h:236
isc::data::ConstElementPtr redactConfig(isc::data::ConstElementPtr const &config)
Redact a configuration.
Definition daemon.cc:278
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.
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_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.