ctrl_dhcp4_srv.cc 13 KB

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