ctrl_dhcp4_srv.cc 13 KB

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