ctrl_dhcp6_srv.cc 14 KB

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