ctrl_dhcp4_srv_unittest.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. // Copyright (C) 2012-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/command_interpreter.h>
  8. #include <config/command_mgr.h>
  9. #include <dhcp/dhcp4.h>
  10. #include <dhcp4/ctrl_dhcp4_srv.h>
  11. #include <dhcp4/tests/dhcp4_test_utils.h>
  12. #include <dhcpsrv/cfgmgr.h>
  13. #include <dhcpsrv/lease.h>
  14. #include <dhcpsrv/lease_mgr_factory.h>
  15. #include <hooks/hooks_manager.h>
  16. #include <stats/stats_mgr.h>
  17. #include <testutils/unix_control_client.h>
  18. #include "marker_file.h"
  19. #include "test_libraries.h"
  20. #include <boost/scoped_ptr.hpp>
  21. #include <gtest/gtest.h>
  22. #include <fstream>
  23. #include <iostream>
  24. #include <sstream>
  25. #include <arpa/inet.h>
  26. #include <unistd.h>
  27. using namespace std;
  28. using namespace isc;
  29. using namespace isc::asiolink;
  30. using namespace isc::config;
  31. using namespace isc::data;
  32. using namespace isc::dhcp;
  33. using namespace isc::dhcp::test;
  34. using namespace isc::hooks;
  35. using namespace isc::stats;
  36. namespace {
  37. class NakedControlledDhcpv4Srv: public ControlledDhcpv4Srv {
  38. // "Naked" DHCPv4 server, exposes internal fields
  39. public:
  40. NakedControlledDhcpv4Srv():ControlledDhcpv4Srv(0) { }
  41. /// Expose internal methods for the sake of testing
  42. using Dhcpv4Srv::receivePacket;
  43. };
  44. /// @brief Fixture class intended for testin control channel in the DHCPv4Srv
  45. class CtrlChannelDhcpv4SrvTest : public ::testing::Test {
  46. public:
  47. /// @brief Path to the UNIX socket being used to communicate with the server
  48. std::string socket_path_;
  49. /// @brief Pointer to the tested server object
  50. boost::shared_ptr<NakedControlledDhcpv4Srv> server_;
  51. /// @brief Default constructor
  52. ///
  53. /// Sets socket path to its default value.
  54. CtrlChannelDhcpv4SrvTest() {
  55. const char* env = getenv("KEA_SOCKET_TEST_DIR");
  56. if (env) {
  57. socket_path_ = string(env) + "/kea4.sock";
  58. } else {
  59. socket_path_ = string(TEST_DATA_BUILDDIR) + "/kea4.sock";
  60. }
  61. reset();
  62. }
  63. /// @brief Destructor
  64. ~CtrlChannelDhcpv4SrvTest() {
  65. LeaseMgrFactory::destroy();
  66. StatsMgr::instance().removeAll();
  67. server_.reset();
  68. reset();
  69. };
  70. void createUnixChannelServer() {
  71. ::remove(socket_path_.c_str());
  72. // Just a simple config. The important part here is the socket
  73. // location information.
  74. std::string header =
  75. "{"
  76. " \"interfaces-config\": {"
  77. " \"interfaces\": [ \"*\" ]"
  78. " },"
  79. " \"expired-leases-processing\": {"
  80. " \"reclaim-timer-wait-time\": 60,"
  81. " \"hold-reclaimed-time\": 500,"
  82. " \"flush-reclaimed-timer-wait-time\": 60"
  83. " },"
  84. " \"rebind-timer\": 2000, "
  85. " \"renew-timer\": 1000, "
  86. " \"subnet4\": [ ],"
  87. " \"valid-lifetime\": 4000,"
  88. " \"control-socket\": {"
  89. " \"socket-type\": \"unix\","
  90. " \"socket-name\": \"";
  91. std::string footer =
  92. "\" },"
  93. " \"lease-database\": {"
  94. " \"type\": \"memfile\", \"persist\": false }"
  95. "}";
  96. // Fill in the socket-name value with socket_path_ to
  97. // make the actual configuration text.
  98. std::string config_txt = header + socket_path_ + footer;
  99. ASSERT_NO_THROW(server_.reset(new NakedControlledDhcpv4Srv()));
  100. ConstElementPtr config;
  101. ASSERT_NO_THROW(config = parseDHCP4(config_txt));
  102. ConstElementPtr answer = server_->processConfig(config);
  103. ASSERT_TRUE(answer);
  104. int status = 0;
  105. ConstElementPtr txt = isc::config::parseAnswer(status, answer);
  106. // This should succeed. If not, print the error message.
  107. ASSERT_EQ(0, status) << txt->str();
  108. // Now check that the socket was indeed open.
  109. ASSERT_GT(isc::config::CommandMgr::instance().getControlSocketFD(), -1);
  110. }
  111. /// @brief Reset hooks data
  112. ///
  113. /// Resets the data for the hooks-related portion of the test by ensuring
  114. /// that no libraries are loaded and that any marker files are deleted.
  115. void reset() {
  116. // Unload any previously-loaded libraries.
  117. HooksManager::unloadLibraries();
  118. // Get rid of any marker files.
  119. static_cast<void>(remove(LOAD_MARKER_FILE));
  120. static_cast<void>(remove(UNLOAD_MARKER_FILE));
  121. IfaceMgr::instance().deleteAllExternalSockets();
  122. CfgMgr::instance().clear();
  123. // Remove unix socket file
  124. ::remove(socket_path_.c_str());
  125. }
  126. /// @brief Conducts a command/response exchange via UnixCommandSocket
  127. ///
  128. /// This method connects to the given server over the given socket path.
  129. /// If successful, it then sends the given command and retrieves the
  130. /// server's response. Note that it calls the server's receivePacket()
  131. /// method where needed to cause the server to process IO events on
  132. /// control channel the control channel sockets.
  133. ///
  134. /// @param command the command text to execute in JSON form
  135. /// @param response variable into which the received response should be
  136. /// placed.
  137. void sendUnixCommand(const std::string& command, std::string& response) {
  138. response = "";
  139. boost::scoped_ptr<UnixControlClient> client;
  140. client.reset(new UnixControlClient());
  141. ASSERT_TRUE(client);
  142. // Connect and then call server's receivePacket() so it can
  143. // detect the control socket connect and call the accept handler
  144. ASSERT_TRUE(client->connectToServer(socket_path_));
  145. ASSERT_NO_THROW(server_->receivePacket(0));
  146. // Send the command and then call server's receivePacket() so it can
  147. // detect the inbound data and call the read handler
  148. ASSERT_TRUE(client->sendCommand(command));
  149. ASSERT_NO_THROW(server_->receivePacket(0));
  150. // Read the response generated by the server. Note that getResponse
  151. // only fails if there an IO error or no response data was present.
  152. // It is not based on the response content.
  153. ASSERT_TRUE(client->getResponse(response));
  154. // Now disconnect and process the close event
  155. client->disconnectFromServer();
  156. ASSERT_NO_THROW(server_->receivePacket(0));
  157. }
  158. };
  159. TEST_F(CtrlChannelDhcpv4SrvTest, commands) {
  160. ASSERT_NO_THROW(
  161. server_.reset(new NakedControlledDhcpv4Srv());
  162. );
  163. // Use empty parameters list
  164. ElementPtr params(new isc::data::MapElement());
  165. int rcode = -1;
  166. // Case 1: send bogus command
  167. ConstElementPtr result = ControlledDhcpv4Srv::processCommand("blah", params);
  168. ConstElementPtr comment = parseAnswer(rcode, result);
  169. EXPECT_EQ(1, rcode); // expect failure (no such command as blah)
  170. // Case 2: send shutdown command without any parameters
  171. result = ControlledDhcpv4Srv::processCommand("shutdown", params);
  172. comment = parseAnswer(rcode, result);
  173. EXPECT_EQ(0, rcode); // expect success
  174. const pid_t pid(getpid());
  175. ConstElementPtr x(new isc::data::IntElement(pid));
  176. params->set("pid", x);
  177. // Case 3: send shutdown command with 1 parameter: pid
  178. result = ControlledDhcpv4Srv::processCommand("shutdown", params);
  179. comment = parseAnswer(rcode, result);
  180. EXPECT_EQ(0, rcode); // expect success
  181. }
  182. // Check that the "libreload" command will reload libraries
  183. TEST_F(CtrlChannelDhcpv4SrvTest, libreload) {
  184. // Sending commands for processing now requires a server that can process
  185. // them.
  186. ASSERT_NO_THROW(
  187. server_.reset(new NakedControlledDhcpv4Srv());
  188. );
  189. // Ensure no marker files to start with.
  190. ASSERT_FALSE(checkMarkerFileExists(LOAD_MARKER_FILE));
  191. ASSERT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));
  192. // Load two libraries
  193. HookLibsCollection libraries;
  194. libraries.push_back(make_pair(CALLOUT_LIBRARY_1, ConstElementPtr()));
  195. libraries.push_back(make_pair(CALLOUT_LIBRARY_2, ConstElementPtr()));
  196. HooksManager::loadLibraries(libraries);
  197. // Check they are loaded.
  198. std::vector<std::string> loaded_libraries =
  199. HooksManager::getLibraryNames();
  200. ASSERT_TRUE(extractNames(libraries) == loaded_libraries);
  201. // ... which also included checking that the marker file created by the
  202. // load functions exists and holds the correct value (of "12" - the
  203. // first library appends "1" to the file, the second appends "2"). Also
  204. // check that the unload marker file does not yet exist.
  205. EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "12"));
  206. EXPECT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));
  207. // Now execute the "libreload" command. This should cause the libraries
  208. // to unload and to reload.
  209. // Use empty parameters list
  210. ElementPtr params(new isc::data::MapElement());
  211. int rcode = -1;
  212. ConstElementPtr result =
  213. ControlledDhcpv4Srv::processCommand("libreload", params);
  214. ConstElementPtr comment = parseAnswer(rcode, result);
  215. EXPECT_EQ(0, rcode); // Expect success
  216. // Check that the libraries have unloaded and reloaded. The libraries are
  217. // unloaded in the reverse order to which they are loaded. When they load,
  218. // they should append information to the loading marker file.
  219. EXPECT_TRUE(checkMarkerFile(UNLOAD_MARKER_FILE, "21"));
  220. EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "1212"));
  221. }
  222. // This test checks which commands are registered by the DHCPv4 server.
  223. TEST_F(CtrlChannelDhcpv4SrvTest, commandsRegistration) {
  224. ConstElementPtr list_cmds = createCommand("list-commands");
  225. ConstElementPtr answer;
  226. // By default the list should be empty (except the standard list-commands
  227. // supported by the CommandMgr itself)
  228. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  229. ASSERT_TRUE(answer);
  230. ASSERT_TRUE(answer->get("arguments"));
  231. EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
  232. // Created server should register several additional commands.
  233. ASSERT_NO_THROW(
  234. server_.reset(new NakedControlledDhcpv4Srv());
  235. );
  236. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  237. ASSERT_TRUE(answer);
  238. ASSERT_TRUE(answer->get("arguments"));
  239. std::string command_list = answer->get("arguments")->str();
  240. EXPECT_TRUE(command_list.find("\"list-commands\"") != string::npos);
  241. EXPECT_TRUE(command_list.find("\"statistic-get\"") != string::npos);
  242. EXPECT_TRUE(command_list.find("\"statistic-get-all\"") != string::npos);
  243. EXPECT_TRUE(command_list.find("\"statistic-remove\"") != string::npos);
  244. EXPECT_TRUE(command_list.find("\"statistic-remove-all\"") != string::npos);
  245. EXPECT_TRUE(command_list.find("\"statistic-reset\"") != string::npos);
  246. EXPECT_TRUE(command_list.find("\"statistic-reset-all\"") != string::npos);
  247. // Ok, and now delete the server. It should deregister its commands.
  248. server_.reset();
  249. // The list should be (almost) empty again.
  250. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  251. ASSERT_TRUE(answer);
  252. ASSERT_TRUE(answer->get("arguments"));
  253. EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
  254. }
  255. // Tests that the server properly responds to invalid commands sent
  256. // via ControlChannel
  257. TEST_F(CtrlChannelDhcpv4SrvTest, controlChannelNegative) {
  258. createUnixChannelServer();
  259. std::string response;
  260. sendUnixCommand("{ \"command\": \"bogus\" }", response);
  261. EXPECT_EQ("{ \"result\": 1,"
  262. " \"text\": \"'bogus' command not supported.\" }", response);
  263. sendUnixCommand("utter nonsense", response);
  264. EXPECT_EQ("{ \"result\": 1, "
  265. "\"text\": \"error: unexpected character u in <string>:1:2\" }",
  266. response);
  267. }
  268. // Tests that the server properly responds to shtudown command sent
  269. // via ControlChannel
  270. TEST_F(CtrlChannelDhcpv4SrvTest, controlChannelShutdown) {
  271. createUnixChannelServer();
  272. std::string response;
  273. sendUnixCommand("{ \"command\": \"shutdown\" }", response);
  274. EXPECT_EQ("{ \"result\": 0, \"text\": \"Shutting down.\" }",response);
  275. }
  276. // This test verifies that the DHCP server immediately reclaims expired
  277. // leases on leases-reclaim command
  278. TEST_F(CtrlChannelDhcpv4SrvTest, controlLeasesReclaim) {
  279. createUnixChannelServer();
  280. // Create expired leases. Leases are expired by 40 seconds ago
  281. // (valid lifetime = 60, cltt = now - 100).
  282. HWAddrPtr hwaddr0(new HWAddr(HWAddr::fromText("00:01:02:03:04:05")));
  283. Lease4Ptr lease0(new Lease4(IOAddress("10.0.0.1"), hwaddr0,
  284. ClientIdPtr(), 60, 10, 20,
  285. time(NULL) - 100, SubnetID(1)));
  286. HWAddrPtr hwaddr1(new HWAddr(HWAddr::fromText("01:02:03:04:05:06")));
  287. Lease4Ptr lease1(new Lease4(IOAddress("10.0.0.2"), hwaddr1,
  288. ClientIdPtr(), 60, 10, 20,
  289. time(NULL) - 100, SubnetID(1)));
  290. // Add leases to the database.
  291. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  292. ASSERT_NO_THROW(lease_mgr.addLease(lease0));
  293. ASSERT_NO_THROW(lease_mgr.addLease(lease1));
  294. // Make sure they have been added.
  295. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.1")));
  296. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.2")));
  297. // No arguments
  298. std::string response;
  299. sendUnixCommand("{ \"command\": \"leases-reclaim\" }", response);
  300. EXPECT_EQ("{ \"result\": 1, \"text\": "
  301. "\"Missing mandatory 'remove' parameter.\" }", response);
  302. // Bad argument name
  303. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  304. "\"arguments\": { \"reclaim\": true } }", response);
  305. EXPECT_EQ("{ \"result\": 1, \"text\": "
  306. "\"Missing mandatory 'remove' parameter.\" }", response);
  307. // Bad remove argument type
  308. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  309. "\"arguments\": { \"remove\": \"bogus\" } }", response);
  310. EXPECT_EQ("{ \"result\": 1, \"text\": "
  311. "\"'remove' parameter expected to be a boolean.\" }", response);
  312. // Send the command
  313. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  314. "\"arguments\": { \"remove\": false } }", response);
  315. EXPECT_EQ("{ \"result\": 0, \"text\": "
  316. "\"Reclamation of expired leases is complete.\" }", response);
  317. // Leases should be reclaimed, but not removed
  318. ASSERT_NO_THROW(lease0 = lease_mgr.getLease4(IOAddress("10.0.0.1")));
  319. ASSERT_NO_THROW(lease1 = lease_mgr.getLease4(IOAddress("10.0.0.2")));
  320. ASSERT_TRUE(lease0);
  321. ASSERT_TRUE(lease1);
  322. EXPECT_TRUE(lease0->stateExpiredReclaimed());
  323. EXPECT_TRUE(lease1->stateExpiredReclaimed());
  324. }
  325. // Thist test verifies that the DHCP server immediately removed expired
  326. // leases on leases-reclaim command with remove = true
  327. TEST_F(CtrlChannelDhcpv4SrvTest, controlLeasesReclaimRemove) {
  328. createUnixChannelServer();
  329. // Create expired leases. Leases are expired by 40 seconds ago
  330. // (valid lifetime = 60, cltt = now - 100).
  331. HWAddrPtr hwaddr0(new HWAddr(HWAddr::fromText("00:01:02:03:04:05")));
  332. Lease4Ptr lease0(new Lease4(IOAddress("10.0.0.1"), hwaddr0,
  333. ClientIdPtr(), 60, 10, 20,
  334. time(NULL) - 100, SubnetID(1)));
  335. HWAddrPtr hwaddr1(new HWAddr(HWAddr::fromText("01:02:03:04:05:06")));
  336. Lease4Ptr lease1(new Lease4(IOAddress("10.0.0.2"), hwaddr1,
  337. ClientIdPtr(), 60, 10, 20,
  338. time(NULL) - 100, SubnetID(1)));
  339. // Add leases to the database.
  340. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  341. ASSERT_NO_THROW(lease_mgr.addLease(lease0));
  342. ASSERT_NO_THROW(lease_mgr.addLease(lease1));
  343. // Make sure they have been added.
  344. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.1")));
  345. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.2")));
  346. // Send the command
  347. std::string response;
  348. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  349. "\"arguments\": { \"remove\": true } }", response);
  350. EXPECT_EQ("{ \"result\": 0, \"text\": "
  351. "\"Reclamation of expired leases is complete.\" }", response);
  352. // Leases should have been removed.
  353. ASSERT_NO_THROW(lease0 = lease_mgr.getLease4(IOAddress("10.0.0.1")));
  354. ASSERT_NO_THROW(lease1 = lease_mgr.getLease4(IOAddress("10.0.0.2")));
  355. EXPECT_FALSE(lease0);
  356. EXPECT_FALSE(lease1);
  357. }
  358. // Tests that the server properly responds to statistics commands. Note this
  359. // is really only intended to verify that the appropriate Statistics handler
  360. // is called based on the command. It is not intended to be an exhaustive
  361. // test of Dhcpv4 statistics.
  362. TEST_F(CtrlChannelDhcpv4SrvTest, controlChannelStats) {
  363. createUnixChannelServer();
  364. std::string response;
  365. // Check statistic-get
  366. sendUnixCommand("{ \"command\" : \"statistic-get\", "
  367. " \"arguments\": {"
  368. " \"name\":\"bogus\" }}", response);
  369. EXPECT_EQ("{ \"arguments\": { }, \"result\": 0 }", response);
  370. // Check statistic-get-all
  371. sendUnixCommand("{ \"command\" : \"statistic-get-all\", "
  372. " \"arguments\": {}}", response);
  373. EXPECT_EQ("{ \"arguments\": { }, \"result\": 0 }", response);
  374. // Check statistic-reset
  375. sendUnixCommand("{ \"command\" : \"statistic-reset\", "
  376. " \"arguments\": {"
  377. " \"name\":\"bogus\" }}", response);
  378. EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
  379. response);
  380. // Check statistic-reset-all
  381. sendUnixCommand("{ \"command\" : \"statistic-reset-all\", "
  382. " \"arguments\": {}}", response);
  383. EXPECT_EQ("{ \"result\": 0, \"text\": "
  384. "\"All statistics reset to neutral values.\" }", response);
  385. // Check statistic-remove
  386. sendUnixCommand("{ \"command\" : \"statistic-remove\", "
  387. " \"arguments\": {"
  388. " \"name\":\"bogus\" }}", response);
  389. EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
  390. response);
  391. // Check statistic-remove-all
  392. sendUnixCommand("{ \"command\" : \"statistic-remove-all\", "
  393. " \"arguments\": {}}", response);
  394. EXPECT_EQ("{ \"result\": 0, \"text\": \"All statistics removed.\" }",
  395. response);
  396. }
  397. } // End of anonymous namespace