Kea 3.1.0
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>
17#include <dhcp/libdhcp++.h>
19#include <dhcp6/dhcp6_log.h>
20#include <dhcp6/dhcp6to4_ipc.h>
25#include <dhcpsrv/cfgmgr.h>
26#include <dhcpsrv/db_type.h>
27#include <dhcpsrv/host_mgr.h>
29#include <hooks/hooks.h>
30#include <hooks/hooks_manager.h>
32#include <stats/stats_mgr.h>
33#include <util/encode/encode.h>
35
36#include <signal.h>
37
38#include <sstream>
39
40using namespace isc::asiolink;
41using namespace isc::config;
42using namespace isc::data;
43using namespace isc::db;
44using namespace isc::dhcp;
45using namespace isc::hooks;
46using namespace isc::stats;
47using namespace isc::util;
48using namespace std;
49namespace ph = std::placeholders;
50
51namespace {
52
54struct CtrlDhcp6Hooks {
55 int hooks_index_dhcp6_srv_configured_;
56
58 CtrlDhcp6Hooks() {
59 hooks_index_dhcp6_srv_configured_ = HooksManager::registerHook("dhcp6_srv_configured");
60 }
61
62};
63
64// Declare a Hooks object. As this is outside any function or method, it
65// will be instantiated (and the constructor run) when the module is loaded.
66// As a result, the hook indexes will be defined before any method in this
67// module is called.
68CtrlDhcp6Hooks Hooks;
69
70// Name of the file holding server identifier.
71static const char* SERVER_DUID_FILE = "kea-dhcp6-serverid";
72
82void signalHandler(int signo) {
83 // SIGHUP signals a request to reconfigure the server.
84 if (signo == SIGHUP) {
86 } else if ((signo == SIGTERM) || (signo == SIGINT)) {
88 }
89}
90
91}
92
93namespace isc {
94namespace dhcp {
95
96ControlledDhcpv6Srv* ControlledDhcpv6Srv::server_ = NULL;
97
98void
99ControlledDhcpv6Srv::init(const std::string& file_name) {
100 // Keep the call timestamp.
101 start_ = boost::posix_time::second_clock::universal_time();
102
103 // Configure the server using JSON file.
104 ConstElementPtr result = loadConfigFile(file_name);
105
106 int rcode;
107 ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
108 if (rcode != CONTROL_RESULT_SUCCESS) {
109 string reason = comment ? comment->stringValue() :
110 "no details available";
111 isc_throw(isc::BadValue, reason);
112 }
113
114 // Set signal handlers. When the SIGHUP is received by the process
115 // the server reconfiguration will be triggered. When SIGTERM or
116 // SIGINT will be received, the server will start shutting down.
117 signal_set_.reset(new IOSignalSet(getIOService(), signalHandler));
118
119 signal_set_->add(SIGINT);
120 signal_set_->add(SIGHUP);
121 signal_set_->add(SIGTERM);
122}
123
125 signal_set_.reset();
126 getIOService()->poll();
127}
128
130ControlledDhcpv6Srv::loadConfigFile(const std::string& file_name) {
131 // This is a configuration backend implementation that reads the
132 // configuration from a JSON file.
133
136
137 // Basic sanity check: file name must not be empty.
138 try {
139 if (file_name.empty()) {
140 // Basic sanity check: file name must not be empty.
141 isc_throw(isc::BadValue, "JSON configuration file not specified."
142 " Please use -c command line option.");
143 }
144
145 // Read contents of the file and parse it as JSON
146 Parser6Context parser;
147 json = parser.parseFile(file_name, Parser6Context::PARSER_DHCP6);
148 if (!json) {
149 isc_throw(isc::BadValue, "no configuration found");
150 }
151
152 // Let's do sanity check before we call json->get() which
153 // works only for map.
154 if (json->getType() != isc::data::Element::map) {
155 isc_throw(isc::BadValue, "Configuration file is expected to be "
156 "a map, i.e., start with { and end with } and contain "
157 "at least an entry called 'Dhcp6' that itself is a map. "
158 << file_name
159 << " is a valid JSON, but its top element is not a map."
160 " Did you forget to add { } around your configuration?");
161 }
162
163 // Use parsed JSON structures to configure the server
164 result = CommandMgr::instance().processCommand(createCommand("config-set", json));
165 if (!result) {
166 // Undetermined status of the configuration. This should never
167 // happen, but as the configureDhcp6Server returns a pointer, it is
168 // theoretically possible that it will return NULL.
169 isc_throw(isc::BadValue, "undefined result of "
170 "process command \"config-set\"");
171 }
172
173 // Now check is the returned result is successful (rcode=0) or not
174 // (see @ref isc::config::parseAnswer).
175 int rcode;
176 ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
177 if (rcode != CONTROL_RESULT_SUCCESS) {
178 string reason = comment ? comment->stringValue() :
179 "no details available";
180 isc_throw(isc::BadValue, reason);
181 }
182 } catch (const std::exception& ex) {
183 // If configuration failed at any stage, we drop the staging
184 // configuration and continue to use the previous one.
186
188 .arg(file_name).arg(ex.what());
189 isc_throw(isc::BadValue, "configuration error using file '"
190 << file_name << "': " << ex.what());
191 }
192
194 .arg(MultiThreadingMgr::instance().getMode() ? "yes" : "no")
195 .arg(MultiThreadingMgr::instance().getThreadPoolSize())
196 .arg(MultiThreadingMgr::instance().getPacketQueueSize());
197
198 return (result);
199}
200
202ControlledDhcpv6Srv::commandShutdownHandler(const string&, ConstElementPtr args) {
205 return (createAnswer(CONTROL_RESULT_ERROR, "Shutdown failure."));
206 }
207
208 int exit_value = 0;
209 if (args) {
210 // @todo Should we go ahead and shutdown even if the args are invalid?
211 if (args->getType() != Element::map) {
212 return (createAnswer(CONTROL_RESULT_ERROR, "Argument must be a map"));
213 }
214
215 ConstElementPtr param = args->get("exit-value");
216 if (param) {
217 if (param->getType() != Element::integer) {
219 "parameter 'exit-value' is not an integer"));
220 }
221
222 exit_value = param->intValue();
223 }
224 }
225
227 return (createAnswer(CONTROL_RESULT_SUCCESS, "Shutting down."));
228}
229
231ControlledDhcpv6Srv::commandConfigReloadHandler(const string&,
232 ConstElementPtr /*args*/) {
233 // Get configuration file name.
235 try {
237 auto result = loadConfigFile(file);
239 return (result);
240 } catch (const std::exception& ex) {
241 // Log the unsuccessful reconfiguration. The reason for failure
242 // should be already logged. Don't rethrow an exception so as
243 // the server keeps working.
245 .arg(file);
247 "Config reload failed: " + string(ex.what())));
248 }
249}
250
252ControlledDhcpv6Srv::commandConfigGetHandler(const string&,
253 ConstElementPtr /*args*/) {
254 ElementPtr config = CfgMgr::instance().getCurrentCfg()->toElement();
255 string hash = BaseCommandMgr::getHash(config);
256 config->set("hash", Element::create(hash));
257
258 return (createAnswer(CONTROL_RESULT_SUCCESS, config));
259}
260
262ControlledDhcpv6Srv::commandConfigHashGetHandler(const string&,
263 ConstElementPtr /*args*/) {
264 ConstElementPtr config = CfgMgr::instance().getCurrentCfg()->toElement();
265
266 string hash = BaseCommandMgr::getHash(config);
267
269 params->set("hash", Element::create(hash));
270 return (createAnswer(CONTROL_RESULT_SUCCESS, params));
271}
272
274ControlledDhcpv6Srv::commandConfigWriteHandler(const string&,
275 ConstElementPtr args) {
276 string filename;
277
278 if (args) {
279 if (args->getType() != Element::map) {
280 return (createAnswer(CONTROL_RESULT_ERROR, "Argument must be a map"));
281 }
282 ConstElementPtr filename_param = args->get("filename");
283 if (filename_param) {
284 if (filename_param->getType() != Element::string) {
286 "passed parameter 'filename' is not a string"));
287 }
288 filename = filename_param->stringValue();
289 }
290 }
291
292 if (filename.empty()) {
293 // filename parameter was not specified, so let's use whatever we remember
294 // from the command-line
295 filename = getConfigFile();
296 if (filename.empty()) {
297 return (createAnswer(CONTROL_RESULT_ERROR, "Unable to determine filename."
298 "Please specify filename explicitly."));
299 }
300 } else {
301 try {
302 checkWriteConfigFile(filename);
303 } catch (const isc::Exception& ex) {
304 std::ostringstream msg;
305 msg << "not allowed to write config into " << filename
306 << ": " << ex.what();
307 return (createAnswer(CONTROL_RESULT_ERROR, msg.str()));
308 }
309 }
310
311 // Ok, it's time to write the file.
312 size_t size = 0;
313 try {
314 ConstElementPtr cfg = CfgMgr::instance().getCurrentCfg()->toElement();
315 size = writeConfigFile(filename, cfg);
316 } catch (const isc::Exception& ex) {
317 return (createAnswer(CONTROL_RESULT_ERROR, string("Error during config-write: ")
318 + ex.what()));
319 }
320 if (size == 0) {
321 return (createAnswer(CONTROL_RESULT_ERROR, "Error writing configuration to "
322 + filename));
323 }
324
325 // Ok, it's time to return the successful response.
327 params->set("size", Element::create(static_cast<long long>(size)));
328 params->set("filename", Element::create(filename));
329
330 return (createAnswer(CONTROL_RESULT_SUCCESS, "Configuration written to "
331 + filename + " successful", params));
332}
333
335ControlledDhcpv6Srv::commandConfigSetHandler(const string&,
336 ConstElementPtr args) {
337 const int status_code = CONTROL_RESULT_ERROR;
338 ConstElementPtr dhcp6;
339 string message;
340
341 // Command arguments are expected to be:
342 // { "Dhcp6": { ... } }
343 if (!args) {
344 message = "Missing mandatory 'arguments' parameter.";
345 } else {
346 dhcp6 = args->get("Dhcp6");
347 if (!dhcp6) {
348 message = "Missing mandatory 'Dhcp6' parameter.";
349 } else if (dhcp6->getType() != Element::map) {
350 message = "'Dhcp6' parameter expected to be a map.";
351 }
352 }
353
354 // Check unsupported objects.
355 if (message.empty()) {
356 for (auto const& obj : args->mapValue()) {
357 const string& obj_name = obj.first;
358 if (obj_name != "Dhcp6") {
360 .arg(obj_name);
361 if (message.empty()) {
362 message = "Unsupported '" + obj_name + "' parameter";
363 } else {
364 message += " (and '" + obj_name + "')";
365 }
366 }
367 }
368 if (!message.empty()) {
369 message += ".";
370 }
371 }
372
373 if (!message.empty()) {
374 // Something is amiss with arguments, return a failure response.
375 ConstElementPtr result = isc::config::createAnswer(status_code,
376 message);
377 return (result);
378 }
379
380 // stop thread pool (if running)
381 MultiThreadingCriticalSection cs;
382
383 // We are starting the configuration process so we should remove any
384 // staging configuration that has been created during previous
385 // configuration attempts.
387
388 // Parse the logger configuration explicitly into the staging config.
389 // Note this does not alter the current loggers, they remain in
390 // effect until we apply the logging config below. If no logging
391 // is supplied logging will revert to default logging.
392 Daemon::configureLogger(dhcp6, CfgMgr::instance().getStagingCfg());
393
394 // Let's apply the new logging. We do it early, so we'll be able to print
395 // out what exactly is wrong with the new config in case of problems.
396 CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
397
398 // Now we configure the server proper.
399 ConstElementPtr result = processConfig(dhcp6);
400
401 // If the configuration parsed successfully, apply the new logger
402 // configuration and the commit the new configuration. We apply
403 // the logging first in case there's a configuration failure.
404 int rcode = 0;
405 isc::config::parseAnswer(rcode, result);
406 if (rcode == CONTROL_RESULT_SUCCESS) {
407 CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
408
409 // Use new configuration.
411 } else if (CfgMgr::instance().getCurrentCfg()->getSequence() != 0) {
412 // Ok, we applied the logging from the upcoming configuration, but
413 // there were problems with the config. As such, we need to back off
414 // and revert to the previous logging configuration. This is not done if
415 // sequence == 0, because that would mean always reverting to stdout by
416 // default, and it is arguably more helpful to have the error in a
417 // potential file or syslog configured in the upcoming configuration.
418 CfgMgr::instance().getCurrentCfg()->applyLoggingCfg();
419
420 // Not initial configuration so someone can believe we reverted
421 // to the previous configuration. It is not the case so be clear
422 // about this.
424 }
425
427 try {
428 // Handle events registered by hooks using external IOService objects.
430 } catch (const std::exception& ex) {
431 std::ostringstream err;
432 err << "Error initializing hooks: "
433 << ex.what();
435 }
436
437 return (result);
438}
439
441ControlledDhcpv6Srv::commandConfigTestHandler(const string&,
442 ConstElementPtr args) {
443 const int status_code = CONTROL_RESULT_ERROR; // 1 indicates an error
444 ConstElementPtr dhcp6;
445 string message;
446
447 // Command arguments are expected to be:
448 // { "Dhcp6": { ... } }
449 if (!args) {
450 message = "Missing mandatory 'arguments' parameter.";
451 } else {
452 dhcp6 = args->get("Dhcp6");
453 if (!dhcp6) {
454 message = "Missing mandatory 'Dhcp6' parameter.";
455 } else if (dhcp6->getType() != Element::map) {
456 message = "'Dhcp6' parameter expected to be a map.";
457 }
458 }
459
460 // Check unsupported objects.
461 if (message.empty()) {
462 for (auto const& obj : args->mapValue()) {
463 const string& obj_name = obj.first;
464 if (obj_name != "Dhcp6") {
466 .arg(obj_name);
467 if (message.empty()) {
468 message = "Unsupported '" + obj_name + "' parameter";
469 } else {
470 message += " (and '" + obj_name + "')";
471 }
472 }
473 }
474 if (!message.empty()) {
475 message += ".";
476 }
477 }
478
479 if (!message.empty()) {
480 // Something is amiss with arguments, return a failure response.
481 ConstElementPtr result = isc::config::createAnswer(status_code,
482 message);
483 return (result);
484 }
485
486 // stop thread pool (if running)
487 MultiThreadingCriticalSection cs;
488
489 // We are starting the configuration process so we should remove any
490 // staging configuration that has been created during previous
491 // configuration attempts.
493
494 // Now we check the server proper.
495 return (checkConfig(dhcp6));
496}
497
499ControlledDhcpv6Srv::commandDhcpDisableHandler(const std::string&,
500 ConstElementPtr args) {
501 std::ostringstream message;
502 int64_t max_period = 0;
503 std::string origin;
504
505 // If the args map does not contain 'origin' parameter, the default type
506 // will be used (user command).
507 auto type = NetworkState::USER_COMMAND;
508
509 // Parse arguments to see if the 'max-period' or 'origin' parameters have
510 // been specified.
511 if (args) {
512 // Arguments must be a map.
513 if (args->getType() != Element::map) {
514 message << "arguments for the 'dhcp-disable' command must be a map";
515
516 } else {
517 ConstElementPtr max_period_element = args->get("max-period");
518 // max-period is optional.
519 if (max_period_element) {
520 // It must be an integer, if specified.
521 if (max_period_element->getType() != Element::integer) {
522 message << "'max-period' argument must be a number";
523
524 } else {
525 // It must be positive integer.
526 max_period = max_period_element->intValue();
527 if (max_period <= 0) {
528 message << "'max-period' must be positive integer";
529 }
530 }
531 }
532 // 'origin-id' replaces the older parameter 'origin' since Kea 2.5.8
533 // stable release. However, the 'origin' is kept for backward compatibility
534 // with Kea versions before 2.5.8. It is common to receive both parameters
535 // because HA hook library sends both in case the partner server hasn't been
536 // upgraded to the new version. The 'origin-id' takes precedence over the
537 // 'origin'.
538 ConstElementPtr origin_id_element = args->get("origin-id");
539 ConstElementPtr origin_element = args->get("origin");
540 // The 'origin-id' and 'origin' arguments are optional.
541 if (origin_id_element) {
542 if (origin_id_element->getType() == Element::integer) {
543 type = origin_id_element->intValue();
544 } else {
545 message << "'origin-id' argument must be a number";
546 }
547 } else if (origin_element) {
548 switch (origin_element->getType()) {
549 case Element::string:
550 origin = origin_element->stringValue();
551 if (origin == "ha-partner") {
553 } else if (origin != "user") {
554 if (origin.empty()) {
555 origin = "(empty string)";
556 }
557 message << "invalid value used for 'origin' parameter: "
558 << origin;
559 }
560 break;
561 case Element::integer:
562 type = origin_element->intValue();
563 break;
564 default:
565 // It must be a string or a number, if specified.
566 message << "'origin' argument must be a string or a number";
567 }
568 }
569 }
570 }
571
572 // No error occurred, so let's disable the service.
573 if (message.tellp() == 0) {
574 message << "DHCPv6 service disabled";
575 if (max_period > 0) {
576 message << " for " << max_period << " seconds";
577
578 // The user specified that the DHCP service should resume not
579 // later than in max-period seconds. If the 'dhcp-enable' command
580 // is not sent, the DHCP service will resume automatically.
581 network_state_->delayedEnableService(static_cast<unsigned>(max_period),
582 type);
583 }
584 network_state_->disableService(type);
585
586 // Success.
587 return (config::createAnswer(CONTROL_RESULT_SUCCESS, message.str()));
588 }
589
590 // Failure.
591 return (config::createAnswer(CONTROL_RESULT_ERROR, message.str()));
592}
593
595ControlledDhcpv6Srv::commandDhcpEnableHandler(const std::string&,
596 ConstElementPtr args) {
597 std::ostringstream message;
598 std::string origin;
599
600 // If the args map does not contain 'origin' parameter, the default type
601 // will be used (user command).
602 auto type = NetworkState::USER_COMMAND;
603
604 // Parse arguments to see if the 'origin' parameter has been specified.
605 if (args) {
606 // Arguments must be a map.
607 if (args->getType() != Element::map) {
608 message << "arguments for the 'dhcp-enable' command must be a map";
609
610 } else {
611 // 'origin-id' replaces the older parameter 'origin' since Kea 2.5.8
612 // stable release. However, the 'origin' is kept for backward compatibility
613 // with Kea versions before 2.5.8. It is common to receive both parameters
614 // because HA hook library sends both in case the partner server hasn't been
615 // upgraded to the new version. The 'origin-id' takes precedence over the
616 // 'origin'.
617 ConstElementPtr origin_id_element = args->get("origin-id");
618 ConstElementPtr origin_element = args->get("origin");
619 // The 'origin-id' and 'origin' arguments are optional.
620 if (origin_id_element) {
621 if (origin_id_element->getType() == Element::integer) {
622 type = origin_id_element->intValue();
623 } else {
624 message << "'origin-id' argument must be a number";
625 }
626 } else if (origin_element) {
627 switch (origin_element->getType()) {
628 case Element::string:
629 origin = origin_element->stringValue();
630 if (origin == "ha-partner") {
632 } else if (origin != "user") {
633 if (origin.empty()) {
634 origin = "(empty string)";
635 }
636 message << "invalid value used for 'origin' parameter: "
637 << origin;
638 }
639 break;
640 case Element::integer:
641 type = origin_element->intValue();
642 break;
643 default:
644 // It must be a string or a number, if specified.
645 message << "'origin' argument must be a string or a number";
646 }
647 }
648 }
649 }
650
651 // No error occurred, so let's enable the service.
652 if (message.tellp() == 0) {
653 network_state_->enableService(type);
654
655 // Success.
657 "DHCP service successfully enabled"));
658 }
659
660 // Failure.
661 return (config::createAnswer(CONTROL_RESULT_ERROR, message.str()));
662}
663
665ControlledDhcpv6Srv::commandVersionGetHandler(const string&, ConstElementPtr) {
667 ElementPtr arguments = Element::createMap();
668 arguments->set("extended", extended);
671 arguments);
672 return (answer);
673}
674
676ControlledDhcpv6Srv::commandBuildReportHandler(const string&,
678 ConstElementPtr answer =
680 return (answer);
681}
682
684ControlledDhcpv6Srv::commandLeasesReclaimHandler(const string&,
685 ConstElementPtr args) {
686 int status_code = CONTROL_RESULT_ERROR;
687 string message;
688
689 // args must be { "remove": <bool> }
690 if (!args) {
691 message = "Missing mandatory 'remove' parameter.";
692 } else {
693 ConstElementPtr remove_name = args->get("remove");
694 if (!remove_name) {
695 message = "Missing mandatory 'remove' parameter.";
696 } else if (remove_name->getType() != Element::boolean) {
697 message = "'remove' parameter expected to be a boolean.";
698 } else {
699 bool remove_lease = remove_name->boolValue();
700 server_->alloc_engine_->reclaimExpiredLeases6(0, 0, remove_lease);
701 status_code = 0;
702 message = "Reclamation of expired leases is complete.";
703 }
704 }
705 ConstElementPtr answer = isc::config::createAnswer(status_code, message);
706 return (answer);
707}
708
710ControlledDhcpv6Srv::commandSubnet6SelectTestHandler(const string&,
711 ConstElementPtr args) {
712 if (!args) {
713 return (createAnswer(CONTROL_RESULT_ERROR, "empty arguments"));
714 }
715 if (args->getType() != Element::map) {
716 return (createAnswer(CONTROL_RESULT_ERROR, "arguments must be a map"));
717 }
718 SubnetSelector selector;
720 for (auto const& entry : args->mapValue()) {
721 ostringstream errmsg;
722 if (entry.first == "interface") {
723 if (entry.second->getType() != Element::string) {
724 errmsg << "'interface' entry must be a string";
725 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
726 }
727 selector.iface_name_ = entry.second->stringValue();
728 continue;
729 } if (entry.first == "interface-id") {
730 if (entry.second->getType() != Element::string) {
731 errmsg << "'interface-id' entry must be a string";
732 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
733 }
734 try {
735 string str = entry.second->stringValue();
736 vector<uint8_t> id = util::str::quotedStringToBinary(str);
737 if (id.empty()) {
739 }
740 if (id.empty()) {
741 errmsg << "'interface-id' must be not empty";
742 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
743 }
744 selector.interface_id_ = OptionPtr(new Option(Option::V6,
746 id));
747 continue;
748 } catch (...) {
749 errmsg << "value of 'interface-id' was not recognized";
750 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
751 }
752 } else if (entry.first == "remote") {
753 if (entry.second->getType() != Element::string) {
754 errmsg << "'remote' entry must be a string";
755 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
756 }
757 try {
758 IOAddress addr(entry.second->stringValue());
759 if (!addr.isV6()) {
760 errmsg << "bad 'remote' entry: not IPv6";
761 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
762 }
763 selector.remote_address_ = addr;
764 continue;
765 } catch (const exception& ex) {
766 errmsg << "bad 'remote' entry: " << ex.what();
767 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
768 }
769 } else if (entry.first == "link") {
770 if (entry.second->getType() != Element::string) {
771 errmsg << "'link' 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 'link' entry: not IPv6";
778 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
779 }
780 selector.first_relay_linkaddr_ = addr;
781 continue;
782 } catch (const exception& ex) {
783 errmsg << "bad 'link' entry: " << ex.what();
784 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
785 }
786 } else if (entry.first == "classes") {
787 if (entry.second->getType() != Element::list) {
789 "'classes' entry must be a list"));
790 }
791 for (auto const& item : entry.second->listValue()) {
792 if (!item || (item->getType() != Element::string)) {
793 errmsg << "'classes' entry must be a list of strings";
794 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
795 }
796 // Skip empty client classes.
797 if (!item->stringValue().empty()) {
798 selector.client_classes_.insert(item->stringValue());
799 }
800 }
801 continue;
802 } else {
803 errmsg << "unknown entry '" << entry.first << "'";
804 return (createAnswer(CONTROL_RESULT_ERROR, errmsg.str()));
805 }
806 }
808 getCfgSubnets6()->selectSubnet(selector);
809 if (!subnet) {
810 return (createAnswer(CONTROL_RESULT_EMPTY, "no subnet selected"));
811 }
812 SharedNetwork6Ptr network;
813 subnet->getSharedNetwork(network);
814 ostringstream msg;
815 if (network) {
816 msg << "selected shared network '" << network->getName()
817 << "' starting with subnet '" << subnet->toText()
818 << "' id " << subnet->getID();
819 } else {
820 msg << "selected subnet '" << subnet->toText()
821 << "' id " << subnet->getID();
822 }
823 return (createAnswer(CONTROL_RESULT_SUCCESS, msg.str()));
824}
825
827ControlledDhcpv6Srv::commandServerTagGetHandler(const std::string&,
829 const std::string& tag =
830 CfgMgr::instance().getCurrentCfg()->getServerTag();
831 ElementPtr response = Element::createMap();
832 response->set("server-tag", Element::create(tag));
833
834 return (createAnswer(CONTROL_RESULT_SUCCESS, response));
835}
836
838ControlledDhcpv6Srv::commandConfigBackendPullHandler(const std::string&,
840 auto ctl_info = CfgMgr::instance().getCurrentCfg()->getConfigControlInfo();
841 if (!ctl_info) {
842 return (createAnswer(CONTROL_RESULT_EMPTY, "No config backend."));
843 }
844
845 // stop thread pool (if running)
846 MultiThreadingCriticalSection cs;
847
848 // Reschedule the periodic CB fetch.
849 if (TimerMgr::instance()->isTimerRegistered("Dhcp6CBFetchTimer")) {
850 TimerMgr::instance()->cancel("Dhcp6CBFetchTimer");
851 TimerMgr::instance()->setup("Dhcp6CBFetchTimer");
852 }
853
854 // Code from cbFetchUpdates.
855 // The configuration to use is the current one because this is called
856 // after the configuration manager commit.
857 try {
858 auto srv_cfg = CfgMgr::instance().getCurrentCfg();
859 auto mode = CBControlDHCPv6::FetchMode::FETCH_UPDATE;
860 server_->getCBControl()->databaseConfigFetch(srv_cfg, mode);
861 } catch (const std::exception& ex) {
863 .arg(ex.what());
865 "On demand configuration update failed: " +
866 string(ex.what())));
867 }
869 "On demand configuration update successful."));
870}
871
873ControlledDhcpv6Srv::commandStatusGetHandler(const string&,
874 ConstElementPtr /*args*/) {
876 status->set("pid", Element::create(static_cast<int>(getpid())));
877
878 auto now = boost::posix_time::second_clock::universal_time();
879 // Sanity check: start_ is always initialized.
880 if (!start_.is_not_a_date_time()) {
881 auto uptime = now - start_;
882 status->set("uptime", Element::create(uptime.total_seconds()));
883 }
884
885 auto last_commit = CfgMgr::instance().getCurrentCfg()->getLastCommitTime();
886 if (!last_commit.is_not_a_date_time()) {
887 auto reload = now - last_commit;
888 status->set("reload", Element::create(reload.total_seconds()));
889 }
890
891 auto& mt_mgr = MultiThreadingMgr::instance();
892 if (mt_mgr.getMode()) {
893 status->set("multi-threading-enabled", Element::create(true));
894 status->set("thread-pool-size", Element::create(static_cast<int32_t>(
895 MultiThreadingMgr::instance().getThreadPoolSize())));
896 status->set("packet-queue-size", Element::create(static_cast<int32_t>(
897 MultiThreadingMgr::instance().getPacketQueueSize())));
898 ElementPtr queue_stats = Element::createList();
899 queue_stats->add(Element::create(mt_mgr.getThreadPool().getQueueStat(10)));
900 queue_stats->add(Element::create(mt_mgr.getThreadPool().getQueueStat(100)));
901 queue_stats->add(Element::create(mt_mgr.getThreadPool().getQueueStat(1000)));
902 status->set("packet-queue-statistics", queue_stats);
903
904 } else {
905 status->set("multi-threading-enabled", Element::create(false));
906 }
907
908 status->set("extended-info-tables", Element::create(
909 CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getExtendedInfoTablesEnabled()));
910
911 // Iterate through the interfaces and get all the errors.
912 ElementPtr socket_errors(Element::createList());
913 for (IfacePtr const& interface : IfaceMgr::instance().getIfaces()) {
914 for (std::string const& error : interface->getErrors()) {
915 socket_errors->add(Element::create(error));
916 }
917 }
918
919 // Abstract the information from all sockets into a single status.
921 if (socket_errors->empty()) {
922 sockets->set("status", Element::create("ready"));
923 } else {
924 ReconnectCtlPtr const reconnect_ctl(
925 CfgMgr::instance().getCurrentCfg()->getCfgIface()->getReconnectCtl());
926 if (reconnect_ctl && reconnect_ctl->retriesLeft()) {
927 sockets->set("status", Element::create("retrying"));
928 } else {
929 sockets->set("status", Element::create("failed"));
930 }
931 sockets->set("errors", socket_errors);
932 }
933 status->set("sockets", sockets);
934
935 status->set("dhcp-state", network_state_->toElement());
936
937 return (createAnswer(CONTROL_RESULT_SUCCESS, status));
938}
939
941ControlledDhcpv6Srv::commandStatisticSetMaxSampleCountAllHandler(const string&,
942 ConstElementPtr args) {
943 StatsMgr& stats_mgr = StatsMgr::instance();
945 // Update the default parameter.
946 long max_samples = stats_mgr.getMaxSampleCountDefault();
947 CfgMgr::instance().getCurrentCfg()->addConfiguredGlobal(
948 "statistic-default-sample-count", Element::create(max_samples));
949 return (answer);
950}
951
953ControlledDhcpv6Srv::commandStatisticSetMaxSampleAgeAllHandler(const string&,
954 ConstElementPtr args) {
955 StatsMgr& stats_mgr = StatsMgr::instance();
957 // Update the default parameter.
958 auto duration = stats_mgr.getMaxSampleAgeDefault();
959 long max_age = toSeconds(duration);
960 CfgMgr::instance().getCurrentCfg()->addConfiguredGlobal(
961 "statistic-default-sample-age", Element::create(max_age));
962 return (answer);
963}
964
968
969 // Allow DB reconnect on startup. The database connection parameters specify
970 // respective details.
972
973 // Single stream instance used in all error clauses
974 std::ostringstream err;
975
976 if (!srv) {
977 err << "Server object not initialized, can't process config.";
979 }
980
982 .arg(srv->redactConfig(config)->str());
983
984 // Destroy lease manager before hooks unload.
986
987 // Destroy host manager before hooks unload.
989
991
992 // Check that configuration was successful. If not, do not reopen sockets
993 // and don't bother with DDNS stuff.
994 try {
995 int rcode = 0;
996 isc::config::parseAnswer(rcode, answer);
997 if (rcode != 0) {
998 return (answer);
999 }
1000 } catch (const std::exception& ex) {
1001 err << "Failed to process configuration:" << ex.what();
1003 }
1004
1005 // Re-open lease and host database with new parameters.
1006 try {
1008 std::bind(&ControlledDhcpv6Srv::dbLostCallback, srv, ph::_1);
1009
1011 std::bind(&ControlledDhcpv6Srv::dbRecoveredCallback, srv, ph::_1);
1012
1014 std::bind(&ControlledDhcpv6Srv::dbFailedCallback, srv, ph::_1);
1015
1016 CfgDbAccessPtr cfg_db = CfgMgr::instance().getStagingCfg()->getCfgDbAccess();
1017 string params = "universe=6";
1018 if (cfg_db->getExtendedInfoTablesEnabled()) {
1019 params += " extended-info-tables=true";
1020 }
1021 cfg_db->setAppendedParameters(params);
1022 cfg_db->createManagers();
1023 // Reset counters related to connections as all managers have been recreated.
1024 srv->getNetworkState()->resetForDbConnection();
1025 srv->getNetworkState()->resetForLocalCommands();
1026 srv->getNetworkState()->resetForRemoteCommands();
1027 } catch (const std::exception& ex) {
1028 err << "Unable to open database: " << ex.what();
1030 }
1031
1032 // Regenerate server identifier if needed.
1033 try {
1034 const std::string duid_file =
1035 std::string(CfgMgr::instance().getDataDir()) + "/" +
1036 std::string(SERVER_DUID_FILE);
1037 DuidPtr duid = CfgMgr::instance().getStagingCfg()->getCfgDUID()->create(duid_file);
1038 server_->serverid_.reset(new Option(Option::V6, D6O_SERVERID, duid->getDuid()));
1039 if (duid) {
1041 .arg(duid->toText())
1042 .arg(duid_file);
1043 }
1044
1045 } catch (const std::exception& ex) {
1046 err << "unable to configure server identifier: " << ex.what();
1048 }
1049
1050 // Server will start DDNS communications if its enabled.
1051 try {
1052 srv->startD2();
1053 } catch (const std::exception& ex) {
1054 err << "Error starting DHCP_DDNS client after server reconfiguration: "
1055 << ex.what();
1057 }
1058
1059 // Setup DHCPv4-over-DHCPv6 IPC
1060 try {
1062 } catch (const std::exception& ex) {
1063 err << "error starting DHCPv4-over-DHCPv6 IPC "
1064 " after server reconfiguration: " << ex.what();
1066 }
1067
1068 // Configure DHCP packet queueing
1069 try {
1071 qc = CfgMgr::instance().getStagingCfg()->getDHCPQueueControl();
1072 if (IfaceMgr::instance().configureDHCPPacketQueue(AF_INET6, qc)) {
1074 .arg(IfaceMgr::instance().getPacketQueue6()->getInfoStr());
1075 }
1076
1077 } catch (const std::exception& ex) {
1078 err << "Error setting packet queue controls after server reconfiguration: "
1079 << ex.what();
1081 }
1082
1083 // Configure a callback to shut down the server when the bind socket
1084 // attempts exceeded.
1086 std::bind(&ControlledDhcpv6Srv::openSocketsFailedCallback, srv, ph::_1);
1087
1088 // Configuration may change active interfaces. Therefore, we have to reopen
1089 // sockets according to new configuration. It is possible that this
1090 // operation will fail for some interfaces but the openSockets function
1091 // guards against exceptions and invokes a callback function to
1092 // log warnings. Since we allow that this fails for some interfaces there
1093 // is no need to rollback configuration if socket fails to open on any
1094 // of the interfaces.
1095 CfgMgr::instance().getStagingCfg()->getCfgIface()->
1096 openSockets(AF_INET6, srv->getServerPort());
1097
1098 // Install the timers for handling leases reclamation.
1099 try {
1100 CfgMgr::instance().getStagingCfg()->getCfgExpiration()->
1101 setupTimers(&ControlledDhcpv6Srv::reclaimExpiredLeases,
1102 &ControlledDhcpv6Srv::deleteExpiredReclaimedLeases,
1103 server_);
1104
1105 } catch (const std::exception& ex) {
1106 err << "unable to setup timers for periodically running the"
1107 " reclamation of the expired leases: "
1108 << ex.what() << ".";
1110 }
1111
1112 // Setup config backend polling, if configured for it.
1113 auto ctl_info = CfgMgr::instance().getStagingCfg()->getConfigControlInfo();
1114 if (ctl_info) {
1115 long fetch_time = static_cast<long>(ctl_info->getConfigFetchWaitTime());
1116 // Only schedule the CB fetch timer if the fetch wait time is greater
1117 // than 0.
1118 if (fetch_time > 0) {
1119 // When we run unit tests, we want to use milliseconds unit for the
1120 // specified interval. Otherwise, we use seconds. Note that using
1121 // milliseconds as a unit in unit tests prevents us from waiting 1
1122 // second on more before the timer goes off. Instead, we wait one
1123 // millisecond which significantly reduces the test time.
1124 if (!server_->inTestMode()) {
1125 fetch_time = 1000 * fetch_time;
1126 }
1127
1128 boost::shared_ptr<unsigned> failure_count(new unsigned(0));
1130 registerTimer("Dhcp6CBFetchTimer",
1131 std::bind(&ControlledDhcpv6Srv::cbFetchUpdates,
1132 server_, CfgMgr::instance().getStagingCfg(),
1133 failure_count),
1134 fetch_time,
1136 TimerMgr::instance()->setup("Dhcp6CBFetchTimer");
1137 }
1138 }
1139
1140 // Finally, we can commit runtime option definitions in libdhcp++. This is
1141 // exception free.
1143
1145 if (notify_libraries) {
1146 return (notify_libraries);
1147 }
1148
1149 // Initialize the allocators. If the user selected a Free Lease Queue Allocator
1150 // for any of the subnets, the server will now populate free leases to the queue.
1151 // It may take a while!
1152 try {
1153 CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->initAllocatorsAfterConfigure();
1154
1155 } catch (const std::exception& ex) {
1156 err << "Error initializing the lease allocators: "
1157 << ex.what();
1159 }
1160
1161 // Apply multi threading settings.
1162 // @note These settings are applied/updated only if no errors occur while
1163 // applying the new configuration.
1164 // @todo This should be fixed.
1165 try {
1166 CfgMultiThreading::apply(CfgMgr::instance().getStagingCfg()->getDHCPMultiThreading());
1167 } catch (const std::exception& ex) {
1168 err << "Error applying multi threading settings: "
1169 << ex.what();
1171 }
1172
1173 return (answer);
1174}
1175
1179 // This hook point notifies hooks libraries that the configuration of the
1180 // DHCPv6 server has completed. It provides the hook library with the pointer
1181 // to the common IO service object, new server configuration in the JSON
1182 // format and with the pointer to the configuration storage where the
1183 // parsed configuration is stored.
1184 if (HooksManager::calloutsPresent(Hooks.hooks_index_dhcp6_srv_configured_)) {
1186
1187 callout_handle->setArgument("io_context", srv->getIOService());
1188 callout_handle->setArgument("network_state", srv->getNetworkState());
1189 callout_handle->setArgument("json_config", config);
1190 callout_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
1191
1192 HooksManager::callCallouts(Hooks.hooks_index_dhcp6_srv_configured_,
1193 *callout_handle);
1194
1195 // If next step is DROP, report a configuration error.
1196 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1197 string error;
1198 try {
1199 callout_handle->getArgument("error", error);
1200 } catch (NoSuchArgument const& ex) {
1201 error = "unknown error";
1202 }
1204 }
1205 }
1206
1207 return (ConstElementPtr());
1208}
1209
1213
1214 if (!srv) {
1216 "Server object not initialized, can't process config.");
1217 return (no_srv);
1218 }
1219
1221 .arg(srv->redactConfig(config)->str());
1222
1223 return (configureDhcp6Server(*srv, config, true));
1224}
1225
1226ControlledDhcpv6Srv::ControlledDhcpv6Srv(uint16_t server_port /*= DHCP6_SERVER_PORT*/,
1227 uint16_t client_port /*= 0*/)
1228 : Dhcpv6Srv(server_port, client_port), timer_mgr_(TimerMgr::instance()) {
1229 if (getInstance()) {
1231 "There is another Dhcpv6Srv instance already.");
1232 }
1233 server_ = this; // remember this instance for later use in handlers
1234
1235 // ProcessSpawn uses IO service to handle signal set events.
1237
1238 // TimerMgr uses IO service to run asynchronous timers.
1239 TimerMgr::instance()->setIOService(getIOService());
1240
1241 // Command managers use IO service to run asynchronous socket operations.
1244
1245 // Set the HTTP default socket address to the IPv6 (vs IPv4) loopback.
1247
1248 // Set the HTTP authentication default realm.
1250
1251 // DatabaseConnection uses IO service to run asynchronous timers.
1253
1254 // These are the commands always supported by the DHCPv6 server.
1255 // Please keep the list in alphabetic order.
1256 CommandMgr::instance().registerCommand("build-report",
1257 std::bind(&ControlledDhcpv6Srv::commandBuildReportHandler, this, ph::_1, ph::_2));
1258
1259 CommandMgr::instance().registerCommand("config-backend-pull",
1260 std::bind(&ControlledDhcpv6Srv::commandConfigBackendPullHandler, this, ph::_1, ph::_2));
1261
1263 std::bind(&ControlledDhcpv6Srv::commandConfigGetHandler, this, ph::_1, ph::_2));
1264
1265 CommandMgr::instance().registerCommand("config-hash-get",
1266 std::bind(&ControlledDhcpv6Srv::commandConfigHashGetHandler, this, ph::_1, ph::_2));
1267
1268 CommandMgr::instance().registerCommand("config-reload",
1269 std::bind(&ControlledDhcpv6Srv::commandConfigReloadHandler, this, ph::_1, ph::_2));
1270
1272 std::bind(&ControlledDhcpv6Srv::commandConfigSetHandler, this, ph::_1, ph::_2));
1273
1274 CommandMgr::instance().registerCommand("config-test",
1275 std::bind(&ControlledDhcpv6Srv::commandConfigTestHandler, this, ph::_1, ph::_2));
1276
1277 CommandMgr::instance().registerCommand("config-write",
1278 std::bind(&ControlledDhcpv6Srv::commandConfigWriteHandler, this, ph::_1, ph::_2));
1279
1280 CommandMgr::instance().registerCommand("dhcp-enable",
1281 std::bind(&ControlledDhcpv6Srv::commandDhcpEnableHandler, this, ph::_1, ph::_2));
1282
1283 CommandMgr::instance().registerCommand("dhcp-disable",
1284 std::bind(&ControlledDhcpv6Srv::commandDhcpDisableHandler, this, ph::_1, ph::_2));
1285
1286 CommandMgr::instance().registerCommand("leases-reclaim",
1287 std::bind(&ControlledDhcpv6Srv::commandLeasesReclaimHandler, this, ph::_1, ph::_2));
1288
1289 CommandMgr::instance().registerCommand("subnet6-select-test",
1290 std::bind(&ControlledDhcpv6Srv::commandSubnet6SelectTestHandler, this, ph::_1, ph::_2));
1291
1292 CommandMgr::instance().registerCommand("server-tag-get",
1293 std::bind(&ControlledDhcpv6Srv::commandServerTagGetHandler, this, ph::_1, ph::_2));
1294
1296 std::bind(&ControlledDhcpv6Srv::commandShutdownHandler, this, ph::_1, ph::_2));
1297
1299 std::bind(&ControlledDhcpv6Srv::commandStatusGetHandler, this, ph::_1, ph::_2));
1300
1301 CommandMgr::instance().registerCommand("version-get",
1302 std::bind(&ControlledDhcpv6Srv::commandVersionGetHandler, this, ph::_1, ph::_2));
1303
1304 // Register statistic related commands
1305 CommandMgr::instance().registerCommand("statistic-get",
1306 std::bind(&StatsMgr::statisticGetHandler, ph::_1, ph::_2));
1307
1308 CommandMgr::instance().registerCommand("statistic-reset",
1309 std::bind(&StatsMgr::statisticResetHandler, ph::_1, ph::_2));
1310
1311 CommandMgr::instance().registerCommand("statistic-remove",
1312 std::bind(&StatsMgr::statisticRemoveHandler, ph::_1, ph::_2));
1313
1314 CommandMgr::instance().registerCommand("statistic-get-all",
1315 std::bind(&StatsMgr::statisticGetAllHandler, ph::_1, ph::_2));
1316
1317 CommandMgr::instance().registerCommand("statistic-reset-all",
1318 std::bind(&StatsMgr::statisticResetAllHandler, ph::_1, ph::_2));
1319
1320 CommandMgr::instance().registerCommand("statistic-remove-all",
1321 std::bind(&StatsMgr::statisticRemoveAllHandler, ph::_1, ph::_2));
1322
1323 CommandMgr::instance().registerCommand("statistic-sample-age-set",
1324 std::bind(&StatsMgr::statisticSetMaxSampleAgeHandler, ph::_1, ph::_2));
1325
1326 CommandMgr::instance().registerCommand("statistic-sample-age-set-all",
1327 std::bind(&ControlledDhcpv6Srv::commandStatisticSetMaxSampleAgeAllHandler, this, ph::_1, ph::_2));
1328
1329 CommandMgr::instance().registerCommand("statistic-sample-count-set",
1330 std::bind(&StatsMgr::statisticSetMaxSampleCountHandler, ph::_1, ph::_2));
1331
1332 CommandMgr::instance().registerCommand("statistic-sample-count-set-all",
1333 std::bind(&ControlledDhcpv6Srv::commandStatisticSetMaxSampleCountAllHandler, this, ph::_1, ph::_2));
1334}
1335
1337 setExitValue(exit_value);
1338 getIOService()->stop(); // Stop ASIO transmissions
1339 shutdown(); // Initiate DHCPv6 shutdown procedure.
1340}
1341
1343 try {
1344 MultiThreadingMgr::instance().apply(false, 0, 0);
1347
1348 // The closure captures either a shared pointer (memory leak)
1349 // or a raw pointer (pointing to a deleted object).
1353
1354 timer_mgr_->unregisterTimers();
1355
1356 cleanup();
1357
1358 // Close command sockets.
1361
1362 // Deregister any registered commands (please keep in alphabetic order)
1363 CommandMgr::instance().deregisterCommand("build-report");
1364 CommandMgr::instance().deregisterCommand("config-backend-pull");
1366 CommandMgr::instance().deregisterCommand("config-hash-get");
1367 CommandMgr::instance().deregisterCommand("config-reload");
1369 CommandMgr::instance().deregisterCommand("config-test");
1370 CommandMgr::instance().deregisterCommand("config-write");
1371 CommandMgr::instance().deregisterCommand("dhcp-disable");
1372 CommandMgr::instance().deregisterCommand("dhcp-enable");
1373 CommandMgr::instance().deregisterCommand("leases-reclaim");
1374 CommandMgr::instance().deregisterCommand("subnet6-select-test");
1375 CommandMgr::instance().deregisterCommand("server-tag-get");
1377 CommandMgr::instance().deregisterCommand("statistic-get");
1378 CommandMgr::instance().deregisterCommand("statistic-get-all");
1379 CommandMgr::instance().deregisterCommand("statistic-remove");
1380 CommandMgr::instance().deregisterCommand("statistic-remove-all");
1381 CommandMgr::instance().deregisterCommand("statistic-reset");
1382 CommandMgr::instance().deregisterCommand("statistic-reset-all");
1383 CommandMgr::instance().deregisterCommand("statistic-sample-age-set");
1384 CommandMgr::instance().deregisterCommand("statistic-sample-age-set-all");
1385 CommandMgr::instance().deregisterCommand("statistic-sample-count-set");
1386 CommandMgr::instance().deregisterCommand("statistic-sample-count-set-all");
1388 CommandMgr::instance().deregisterCommand("version-get");
1389
1390 // Reset DatabaseConnection IO service.
1392 } catch (...) {
1393 // Don't want to throw exceptions from the destructor. The server
1394 // is shutting down anyway.
1395 }
1396
1397 server_ = NULL; // forget this instance. There should be no callback anymore
1398 // at this stage anyway.
1399}
1400
1401void
1402ControlledDhcpv6Srv::reclaimExpiredLeases(const size_t max_leases,
1403 const uint16_t timeout,
1404 const bool remove_lease,
1405 const uint16_t max_unwarned_cycles) {
1406 try {
1407 if (network_state_->isServiceEnabled()) {
1408 server_->alloc_engine_->reclaimExpiredLeases6(max_leases, timeout,
1409 remove_lease,
1410 max_unwarned_cycles);
1411 } else {
1413 .arg(CfgMgr::instance().getCurrentCfg()->
1414 getCfgExpiration()->getReclaimTimerWaitTime());
1415 }
1416 } catch (const std::exception& ex) {
1418 .arg(ex.what());
1419 }
1420 // We're using the ONE_SHOT timer so there is a need to re-schedule it.
1422}
1423
1424void
1425ControlledDhcpv6Srv::deleteExpiredReclaimedLeases(const uint32_t secs) {
1426 if (network_state_->isServiceEnabled()) {
1427 server_->alloc_engine_->deleteExpiredReclaimedLeases6(secs);
1428 }
1429
1430 // We're using the ONE_SHOT timer so there is a need to re-schedule it.
1432}
1433
1434bool
1435ControlledDhcpv6Srv::dbLostCallback(ReconnectCtlPtr db_reconnect_ctl) {
1436 if (!db_reconnect_ctl) {
1437 // This should never happen
1439 return (false);
1440 }
1441
1442 // Disable service until the connection is recovered.
1443 if (db_reconnect_ctl->retriesLeft() == db_reconnect_ctl->maxRetries() &&
1444 db_reconnect_ctl->alterServiceState()) {
1445 network_state_->disableService(NetworkState::DB_CONNECTION + db_reconnect_ctl->id());
1446 }
1447
1449 .arg(db_reconnect_ctl->id())
1450 .arg(db_reconnect_ctl->timerName());
1451
1452 // If reconnect isn't enabled log it, initiate a shutdown if needed and
1453 // return false.
1454 if (!db_reconnect_ctl->retriesLeft() ||
1455 !db_reconnect_ctl->retryInterval()) {
1457 .arg(db_reconnect_ctl->retriesLeft())
1458 .arg(db_reconnect_ctl->retryInterval())
1459 .arg(db_reconnect_ctl->id())
1460 .arg(db_reconnect_ctl->timerName());
1461 if (db_reconnect_ctl->exitOnFailure()) {
1462 shutdownServer(EXIT_FAILURE);
1463 }
1464 return (false);
1465 }
1466
1467 return (true);
1468}
1469
1470bool
1471ControlledDhcpv6Srv::dbRecoveredCallback(ReconnectCtlPtr db_reconnect_ctl) {
1472 if (!db_reconnect_ctl) {
1473 // This should never happen
1475 return (false);
1476 }
1477
1478 // Enable service after the connection is recovered.
1479 if (db_reconnect_ctl->retriesLeft() != db_reconnect_ctl->maxRetries() &&
1480 db_reconnect_ctl->alterServiceState()) {
1481 network_state_->enableService(NetworkState::DB_CONNECTION + db_reconnect_ctl->id());
1482 }
1483
1485 .arg(db_reconnect_ctl->id())
1486 .arg(db_reconnect_ctl->timerName());
1487
1488 db_reconnect_ctl->resetRetries();
1489
1490 return (true);
1491}
1492
1493bool
1494ControlledDhcpv6Srv::dbFailedCallback(ReconnectCtlPtr db_reconnect_ctl) {
1495 if (!db_reconnect_ctl) {
1496 // This should never happen
1498 return (false);
1499 }
1500
1502 .arg(db_reconnect_ctl->maxRetries())
1503 .arg(db_reconnect_ctl->id())
1504 .arg(db_reconnect_ctl->timerName());
1505
1506 if (db_reconnect_ctl->exitOnFailure()) {
1507 shutdownServer(EXIT_FAILURE);
1508 }
1509
1510 return (true);
1511}
1512
1513void
1514ControlledDhcpv6Srv::openSocketsFailedCallback(ReconnectCtlPtr reconnect_ctl) {
1515 if (!reconnect_ctl) {
1516 // This should never happen
1518 return;
1519 }
1520
1522 .arg(reconnect_ctl->maxRetries());
1523
1524 if (reconnect_ctl->exitOnFailure()) {
1525 shutdownServer(EXIT_FAILURE);
1526 }
1527}
1528
1529void
1530ControlledDhcpv6Srv::cbFetchUpdates(const SrvConfigPtr& srv_cfg,
1531 boost::shared_ptr<unsigned> failure_count) {
1532 // stop thread pool (if running)
1533 MultiThreadingCriticalSection cs;
1534
1535 try {
1536 // Fetch any configuration backend updates since our last fetch.
1537 server_->getCBControl()->databaseConfigFetch(srv_cfg,
1538 CBControlDHCPv6::FetchMode::FETCH_UPDATE);
1539 (*failure_count) = 0;
1540
1541 } catch (const std::exception& ex) {
1543 .arg(ex.what());
1544
1545 // We allow at most 10 consecutive failures after which we stop
1546 // making further attempts to fetch the configuration updates.
1547 // Let's return without re-scheduling the timer.
1548 if (++(*failure_count) > 10) {
1551 return;
1552 }
1553 }
1554
1555 // Reschedule the timer to fetch new updates or re-try if
1556 // the previous attempt resulted in an error.
1557 if (TimerMgr::instance()->isTimerRegistered("Dhcp6CBFetchTimer")) {
1558 TimerMgr::instance()->setup("Dhcp6CBFetchTimer");
1559 }
1560}
1561
1562} // namespace dhcp
1563} // 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.
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:159
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 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.