ctrl_dhcp6_srv.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // Copyright (C) 2014-2016 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. #include <config.h>
  7. #include <cc/data.h>
  8. #include <config/command_mgr.h>
  9. #include <dhcp/libdhcp++.h>
  10. #include <dhcpsrv/cfgmgr.h>
  11. #include <dhcpsrv/cfg_db_access.h>
  12. #include <dhcp6/ctrl_dhcp6_srv.h>
  13. #include <dhcp6/dhcp6to4_ipc.h>
  14. #include <dhcp6/dhcp6_log.h>
  15. #include <dhcp6/json_config_parser.h>
  16. #include <hooks/hooks_manager.h>
  17. #include <stats/stats_mgr.h>
  18. using namespace isc::config;
  19. using namespace isc::data;
  20. using namespace isc::hooks;
  21. using namespace isc::stats;
  22. using namespace std;
  23. namespace {
  24. // Name of the file holding server identifier.
  25. static const char* SERVER_DUID_FILE = "kea-dhcp6-serverid";
  26. }
  27. namespace isc {
  28. namespace dhcp {
  29. ControlledDhcpv6Srv* ControlledDhcpv6Srv::server_ = NULL;
  30. ConstElementPtr
  31. ControlledDhcpv6Srv::commandShutdownHandler(const string&, ConstElementPtr) {
  32. if (ControlledDhcpv6Srv::server_) {
  33. ControlledDhcpv6Srv::server_->shutdown();
  34. } else {
  35. LOG_WARN(dhcp6_logger, DHCP6_NOT_RUNNING);
  36. ConstElementPtr answer = isc::config::createAnswer(1, "Shutdown failure.");
  37. return (answer);
  38. }
  39. ConstElementPtr answer = isc::config::createAnswer(0, "Shutting down.");
  40. return (answer);
  41. }
  42. ConstElementPtr
  43. ControlledDhcpv6Srv::commandLibReloadHandler(const string&, ConstElementPtr) {
  44. /// @todo delete any stored CalloutHandles referring to the old libraries
  45. /// Get list of currently loaded libraries and reload them.
  46. HookLibsCollection loaded = HooksManager::getLibraryInfo();
  47. bool status = HooksManager::loadLibraries(loaded);
  48. if (!status) {
  49. LOG_ERROR(dhcp6_logger, DHCP6_HOOKS_LIBS_RELOAD_FAIL);
  50. ConstElementPtr answer = isc::config::createAnswer(1,
  51. "Failed to reload hooks libraries.");
  52. return (answer);
  53. }
  54. ConstElementPtr answer = isc::config::createAnswer(0,
  55. "Hooks libraries successfully reloaded.");
  56. return (answer);
  57. }
  58. ConstElementPtr
  59. ControlledDhcpv6Srv::commandConfigReloadHandler(const string&, ConstElementPtr args) {
  60. return (processConfig(args));
  61. }
  62. ConstElementPtr
  63. ControlledDhcpv6Srv::commandLeasesReclaimHandler(const string&,
  64. ConstElementPtr args) {
  65. int status_code = 1;
  66. string message;
  67. // args must be { "remove": <bool> }
  68. if (!args) {
  69. message = "Missing mandatory 'remove' parameter.";
  70. } else {
  71. ConstElementPtr remove_name = args->get("remove");
  72. if (!remove_name) {
  73. message = "Missing mandatory 'remove' parameter.";
  74. } else if (remove_name->getType() != Element::boolean) {
  75. message = "'remove' parameter expected to be a boolean.";
  76. } else {
  77. bool remove_lease = remove_name->boolValue();
  78. server_->alloc_engine_->reclaimExpiredLeases6(0, 0, remove_lease);
  79. status_code = 0;
  80. message = "Reclamation of expired leases is complete.";
  81. }
  82. }
  83. ConstElementPtr answer = isc::config::createAnswer(status_code, message);
  84. return (answer);
  85. }
  86. isc::data::ConstElementPtr
  87. ControlledDhcpv6Srv::processCommand(const std::string& command,
  88. isc::data::ConstElementPtr args) {
  89. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_COMMAND_RECEIVED)
  90. .arg(command).arg(args->str());
  91. ControlledDhcpv6Srv* srv = ControlledDhcpv6Srv::getInstance();
  92. if (!srv) {
  93. ConstElementPtr no_srv = isc::config::createAnswer(1,
  94. "Server object not initialized, can't process command '" +
  95. command + "'.");
  96. return (no_srv);
  97. }
  98. try {
  99. if (command == "shutdown") {
  100. return (srv->commandShutdownHandler(command, args));
  101. } else if (command == "libreload") {
  102. return (srv->commandLibReloadHandler(command, args));
  103. } else if (command == "config-reload") {
  104. return (srv->commandConfigReloadHandler(command, args));
  105. } else if (command == "leases-reclaim") {
  106. return (srv->commandLeasesReclaimHandler(command, args));
  107. }
  108. return (isc::config::createAnswer(1, "Unrecognized command:"
  109. + command));
  110. } catch (const Exception& ex) {
  111. return (isc::config::createAnswer(1, "Error while processing command '"
  112. + command + "':" + ex.what()));
  113. }
  114. }
  115. isc::data::ConstElementPtr
  116. ControlledDhcpv6Srv::processConfig(isc::data::ConstElementPtr config) {
  117. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_RECEIVED)
  118. .arg(config->str());
  119. ControlledDhcpv6Srv* srv = ControlledDhcpv6Srv::getInstance();
  120. if (!srv) {
  121. ConstElementPtr no_srv = isc::config::createAnswer(1,
  122. "Server object not initialized, can't process config.");
  123. return (no_srv);
  124. }
  125. // We're going to modify the timers configuration. This is not allowed
  126. // when the thread is running.
  127. try {
  128. TimerMgr::instance()->stopThread();
  129. } catch (const std::exception& ex) {
  130. std::ostringstream err;
  131. err << "Unable to stop worker thread running timers: "
  132. << ex.what() << ".";
  133. return (isc::config::createAnswer(1, err.str()));
  134. }
  135. ConstElementPtr answer = configureDhcp6Server(*srv, config);
  136. // Check that configuration was successful. If not, do not reopen sockets
  137. // and don't bother with DDNS stuff.
  138. try {
  139. int rcode = 0;
  140. isc::config::parseAnswer(rcode, answer);
  141. if (rcode != 0) {
  142. return (answer);
  143. }
  144. } catch (const std::exception& ex) {
  145. return (isc::config::createAnswer(1, "Failed to process configuration:"
  146. + string(ex.what())));
  147. }
  148. // Re-open lease and host database with new parameters.
  149. try {
  150. CfgDbAccessPtr cfg_db = CfgMgr::instance().getStagingCfg()->getCfgDbAccess();
  151. cfg_db->setAppendedParameters("universe=6");
  152. cfg_db->createManagers();
  153. } catch (const std::exception& ex) {
  154. return (isc::config::createAnswer(1, "Unable to open database: "
  155. + std::string(ex.what())));
  156. }
  157. // Regenerate server identifier if needed.
  158. try {
  159. const std::string duid_file = CfgMgr::instance().getDataDir() + "/" +
  160. std::string(SERVER_DUID_FILE);
  161. DuidPtr duid = CfgMgr::instance().getStagingCfg()->getCfgDUID()->create(duid_file);
  162. server_->serverid_.reset(new Option(Option::V6, D6O_SERVERID, duid->getDuid()));
  163. if (duid) {
  164. LOG_INFO(dhcp6_logger, DHCP6_USING_SERVERID)
  165. .arg(duid->toText())
  166. .arg(duid_file);
  167. }
  168. } catch (const std::exception& ex) {
  169. std::ostringstream err;
  170. err << "unable to configure server identifier: " << ex.what();
  171. return (isc::config::createAnswer(1, err.str()));
  172. }
  173. // Server will start DDNS communications if its enabled.
  174. try {
  175. srv->startD2();
  176. } catch (const std::exception& ex) {
  177. std::ostringstream err;
  178. err << "error starting DHCP_DDNS client "
  179. " after server reconfiguration: " << ex.what();
  180. return (isc::config::createAnswer(1, err.str()));
  181. }
  182. // Setup DHCPv4-over-DHCPv6 IPC
  183. try {
  184. Dhcp6to4Ipc::instance().open();
  185. } catch (const std::exception& ex) {
  186. std::ostringstream err;
  187. err << "error starting DHCPv4-over-DHCPv6 IPC "
  188. " after server reconfiguration: " << ex.what();
  189. return (isc::config::createAnswer(1, err.str()));
  190. }
  191. // Configuration may change active interfaces. Therefore, we have to reopen
  192. // sockets according to new configuration. It is possible that this
  193. // operation will fail for some interfaces but the openSockets function
  194. // guards against exceptions and invokes a callback function to
  195. // log warnings. Since we allow that this fails for some interfaces there
  196. // is no need to rollback configuration if socket fails to open on any
  197. // of the interfaces.
  198. CfgMgr::instance().getStagingCfg()->getCfgIface()->openSockets(AF_INET6, srv->getPort());
  199. // Install the timers for handling leases reclamation.
  200. try {
  201. CfgMgr::instance().getStagingCfg()->getCfgExpiration()->
  202. setupTimers(&ControlledDhcpv6Srv::reclaimExpiredLeases,
  203. &ControlledDhcpv6Srv::deleteExpiredReclaimedLeases,
  204. server_);
  205. } catch (const std::exception& ex) {
  206. std::ostringstream err;
  207. err << "unable to setup timers for periodically running the"
  208. " reclamation of the expired leases: "
  209. << ex.what() << ".";
  210. return (isc::config::createAnswer(1, err.str()));
  211. }
  212. // Start worker thread if there are any timers installed.
  213. if (TimerMgr::instance()->timersCount() > 0) {
  214. try {
  215. TimerMgr::instance()->startThread();
  216. } catch (const std::exception& ex) {
  217. std::ostringstream err;
  218. err << "Unable to start worker thread running timers: "
  219. << ex.what() << ".";
  220. return (isc::config::createAnswer(1, err.str()));
  221. }
  222. }
  223. // Finally, we can commit runtime option definitions in libdhcp++. This is
  224. // exception free.
  225. LibDHCP::commitRuntimeOptionDefs();
  226. return (answer);
  227. }
  228. ControlledDhcpv6Srv::ControlledDhcpv6Srv(uint16_t port)
  229. : Dhcpv6Srv(port), io_service_(), timer_mgr_(TimerMgr::instance()) {
  230. if (server_) {
  231. isc_throw(InvalidOperation,
  232. "There is another Dhcpv6Srv instance already.");
  233. }
  234. server_ = this; // remember this instance for use in callback
  235. // Register supported commands in CommandMgr
  236. CommandMgr::instance().registerCommand("shutdown",
  237. boost::bind(&ControlledDhcpv6Srv::commandShutdownHandler, this, _1, _2));
  238. /// @todo: register config-reload (see CtrlDhcpv4Srv::commandConfigReloadHandler)
  239. /// @todo: register libreload (see CtrlDhcpv4Srv::commandLibReloadHandler)
  240. CommandMgr::instance().registerCommand("leases-reclaim",
  241. boost::bind(&ControlledDhcpv6Srv::commandLeasesReclaimHandler, this, _1, _2));
  242. // Register statistic related commands
  243. CommandMgr::instance().registerCommand("statistic-get",
  244. boost::bind(&StatsMgr::statisticGetHandler, _1, _2));
  245. CommandMgr::instance().registerCommand("statistic-reset",
  246. boost::bind(&StatsMgr::statisticResetHandler, _1, _2));
  247. CommandMgr::instance().registerCommand("statistic-remove",
  248. boost::bind(&StatsMgr::statisticRemoveHandler, _1, _2));
  249. CommandMgr::instance().registerCommand("statistic-get-all",
  250. boost::bind(&StatsMgr::statisticGetAllHandler, _1, _2));
  251. CommandMgr::instance().registerCommand("statistic-reset-all",
  252. boost::bind(&StatsMgr::statisticResetAllHandler, _1, _2));
  253. CommandMgr::instance().registerCommand("statistic-remove-all",
  254. boost::bind(&StatsMgr::statisticRemoveAllHandler, _1, _2));
  255. }
  256. void ControlledDhcpv6Srv::shutdown() {
  257. io_service_.stop(); // Stop ASIO transmissions
  258. Dhcpv6Srv::shutdown(); // Initiate DHCPv6 shutdown procedure.
  259. }
  260. ControlledDhcpv6Srv::~ControlledDhcpv6Srv() {
  261. try {
  262. cleanup();
  263. // Stop worker thread running timers, if it is running. Then
  264. // unregister any timers.
  265. timer_mgr_->stopThread();
  266. timer_mgr_->unregisterTimers();
  267. // Close the command socket (if it exists).
  268. CommandMgr::instance().closeCommandSocket();
  269. // Deregister any registered commands
  270. CommandMgr::instance().deregisterCommand("shutdown");
  271. CommandMgr::instance().deregisterCommand("leases-reclaim");
  272. CommandMgr::instance().deregisterCommand("statistic-get");
  273. CommandMgr::instance().deregisterCommand("statistic-reset");
  274. CommandMgr::instance().deregisterCommand("statistic-remove");
  275. CommandMgr::instance().deregisterCommand("statistic-get-all");
  276. CommandMgr::instance().deregisterCommand("statistic-reset-all");
  277. CommandMgr::instance().deregisterCommand("statistic-remove-all");
  278. } catch (...) {
  279. // Don't want to throw exceptions from the destructor. The server
  280. // is shutting down anyway.
  281. ;
  282. }
  283. server_ = NULL; // forget this instance. There should be no callback anymore
  284. // at this stage anyway.
  285. }
  286. void ControlledDhcpv6Srv::sessionReader(void) {
  287. // Process one asio event. If there are more events, iface_mgr will call
  288. // this callback more than once.
  289. if (server_) {
  290. server_->io_service_.run_one();
  291. }
  292. }
  293. void
  294. ControlledDhcpv6Srv::reclaimExpiredLeases(const size_t max_leases,
  295. const uint16_t timeout,
  296. const bool remove_lease,
  297. const uint16_t max_unwarned_cycles) {
  298. server_->alloc_engine_->reclaimExpiredLeases6(max_leases, timeout,
  299. remove_lease,
  300. max_unwarned_cycles);
  301. // We're using the ONE_SHOT timer so there is a need to re-schedule it.
  302. TimerMgr::instance()->setup(CfgExpiration::RECLAIM_EXPIRED_TIMER_NAME);
  303. }
  304. void
  305. ControlledDhcpv6Srv::deleteExpiredReclaimedLeases(const uint32_t secs) {
  306. server_->alloc_engine_->deleteExpiredReclaimedLeases6(secs);
  307. // We're using the ONE_SHOT timer so there is a need to re-schedule it.
  308. TimerMgr::instance()->setup(CfgExpiration::FLUSH_RECLAIMED_TIMER_NAME);
  309. }
  310. }; // end of isc::dhcp namespace
  311. }; // end of isc namespace