ctrl_dhcp4_srv_unittest.cc 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. // Copyright (C) 2012-2017 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 <log/logger_support.h>
  17. #include <stats/stats_mgr.h>
  18. #include <testutils/io_utils.h>
  19. #include <testutils/unix_control_client.h>
  20. #include "marker_file.h"
  21. #include "test_libraries.h"
  22. #include <boost/scoped_ptr.hpp>
  23. #include <gtest/gtest.h>
  24. #include <fstream>
  25. #include <iostream>
  26. #include <sstream>
  27. #include <arpa/inet.h>
  28. #include <unistd.h>
  29. using namespace std;
  30. using namespace isc;
  31. using namespace isc::asiolink;
  32. using namespace isc::config;
  33. using namespace isc::data;
  34. using namespace isc::dhcp;
  35. using namespace isc::dhcp::test;
  36. using namespace isc::hooks;
  37. using namespace isc::stats;
  38. using namespace isc::test;
  39. namespace {
  40. class NakedControlledDhcpv4Srv: public ControlledDhcpv4Srv {
  41. // "Naked" DHCPv4 server, exposes internal fields
  42. public:
  43. NakedControlledDhcpv4Srv():ControlledDhcpv4Srv(0) { }
  44. /// Expose internal methods for the sake of testing
  45. using Dhcpv4Srv::receivePacket;
  46. };
  47. /// @brief Fixture class intended for testin control channel in the DHCPv4Srv
  48. class CtrlChannelDhcpv4SrvTest : public ::testing::Test {
  49. public:
  50. /// @brief Path to the UNIX socket being used to communicate with the server
  51. std::string socket_path_;
  52. /// @brief Pointer to the tested server object
  53. boost::shared_ptr<NakedControlledDhcpv4Srv> server_;
  54. /// @brief Default constructor
  55. ///
  56. /// Sets socket path to its default value.
  57. CtrlChannelDhcpv4SrvTest() {
  58. const char* env = getenv("KEA_SOCKET_TEST_DIR");
  59. if (env) {
  60. socket_path_ = string(env) + "/kea4.sock";
  61. } else {
  62. socket_path_ = string(TEST_DATA_BUILDDIR) + "/kea4.sock";
  63. }
  64. reset();
  65. }
  66. /// @brief Destructor
  67. ~CtrlChannelDhcpv4SrvTest() {
  68. LeaseMgrFactory::destroy();
  69. StatsMgr::instance().removeAll();
  70. server_.reset();
  71. reset();
  72. };
  73. void createUnixChannelServer() {
  74. ::remove(socket_path_.c_str());
  75. // Just a simple config. The important part here is the socket
  76. // location information.
  77. std::string header =
  78. "{"
  79. " \"interfaces-config\": {"
  80. " \"interfaces\": [ \"*\" ]"
  81. " },"
  82. " \"expired-leases-processing\": {"
  83. " \"reclaim-timer-wait-time\": 60,"
  84. " \"hold-reclaimed-time\": 500,"
  85. " \"flush-reclaimed-timer-wait-time\": 60"
  86. " },"
  87. " \"rebind-timer\": 2000, "
  88. " \"renew-timer\": 1000, "
  89. " \"subnet4\": [ ],"
  90. " \"valid-lifetime\": 4000,"
  91. " \"control-socket\": {"
  92. " \"socket-type\": \"unix\","
  93. " \"socket-name\": \"";
  94. std::string footer =
  95. "\" },"
  96. " \"lease-database\": {"
  97. " \"type\": \"memfile\", \"persist\": false }"
  98. "}";
  99. // Fill in the socket-name value with socket_path_ to
  100. // make the actual configuration text.
  101. std::string config_txt = header + socket_path_ + footer;
  102. ASSERT_NO_THROW(server_.reset(new NakedControlledDhcpv4Srv()));
  103. ConstElementPtr config;
  104. ASSERT_NO_THROW(config = parseDHCP4(config_txt));
  105. ConstElementPtr answer = server_->processConfig(config);
  106. // Commit the configuration so any subsequent reconfigurations
  107. // will only close the command channel if its configuration has
  108. // changed.
  109. CfgMgr::instance().commit();
  110. ASSERT_TRUE(answer);
  111. int status = 0;
  112. ConstElementPtr txt = isc::config::parseAnswer(status, answer);
  113. // This should succeed. If not, print the error message.
  114. ASSERT_EQ(0, status) << txt->str();
  115. // Now check that the socket was indeed open.
  116. ASSERT_GT(isc::config::CommandMgr::instance().getControlSocketFD(), -1);
  117. }
  118. /// @brief Reset hooks data
  119. ///
  120. /// Resets the data for the hooks-related portion of the test by ensuring
  121. /// that no libraries are loaded and that any marker files are deleted.
  122. void reset() {
  123. // Unload any previously-loaded libraries.
  124. HooksManager::unloadLibraries();
  125. // Get rid of any marker files.
  126. static_cast<void>(remove(LOAD_MARKER_FILE));
  127. static_cast<void>(remove(UNLOAD_MARKER_FILE));
  128. IfaceMgr::instance().deleteAllExternalSockets();
  129. CfgMgr::instance().clear();
  130. // Remove unix socket file
  131. ::remove(socket_path_.c_str());
  132. }
  133. /// @brief Conducts a command/response exchange via UnixCommandSocket
  134. ///
  135. /// This method connects to the given server over the given socket path.
  136. /// If successful, it then sends the given command and retrieves the
  137. /// server's response. Note that it calls the server's receivePacket()
  138. /// method where needed to cause the server to process IO events on
  139. /// control channel the control channel sockets.
  140. ///
  141. /// @param command the command text to execute in JSON form
  142. /// @param response variable into which the received response should be
  143. /// placed.
  144. void sendUnixCommand(const std::string& command, std::string& response) {
  145. response = "";
  146. boost::scoped_ptr<UnixControlClient> client;
  147. client.reset(new UnixControlClient());
  148. ASSERT_TRUE(client);
  149. // Connect and then call server's receivePacket() so it can
  150. // detect the control socket connect and call the accept handler
  151. ASSERT_TRUE(client->connectToServer(socket_path_));
  152. ASSERT_NO_THROW(server_->receivePacket(0));
  153. // Send the command and then call server's receivePacket() so it can
  154. // detect the inbound data and call the read handler
  155. ASSERT_TRUE(client->sendCommand(command));
  156. ASSERT_NO_THROW(server_->receivePacket(0));
  157. // Read the response generated by the server. Note that getResponse
  158. // only fails if there an IO error or no response data was present.
  159. // It is not based on the response content.
  160. ASSERT_TRUE(client->getResponse(response));
  161. // Now disconnect and process the close event
  162. client->disconnectFromServer();
  163. ASSERT_NO_THROW(server_->receivePacket(0));
  164. }
  165. /// @brief Checks response for list-commands
  166. ///
  167. /// This method checks if the list-commands response is generally sane
  168. /// and whether specified command is mentioned in the response.
  169. ///
  170. /// @param rsp response sent back by the server
  171. /// @param command command expected to be on the list.
  172. void checkListCommands(const ConstElementPtr& rsp, const std::string& command) {
  173. ConstElementPtr params;
  174. int status_code = -1;
  175. EXPECT_NO_THROW(params = parseAnswer(status_code, rsp));
  176. EXPECT_EQ(CONTROL_RESULT_SUCCESS, status_code);
  177. ASSERT_TRUE(params);
  178. ASSERT_EQ(Element::list, params->getType());
  179. int cnt = 0;
  180. for (size_t i = 0; i < params->size(); ++i) {
  181. string tmp = params->get(i)->stringValue();
  182. if (tmp == command) {
  183. // Command found, but that's not enough. Need to continue working
  184. // through the list to see if there are no duplicates.
  185. cnt++;
  186. }
  187. }
  188. // Exactly one command on the list is expected.
  189. EXPECT_EQ(1, cnt) << "Command " << command << " not found";
  190. }
  191. /// @brief Check if the answer for write-config command is correct
  192. ///
  193. /// @param response_txt response in text form (as read from the control socket)
  194. /// @param exp_status expected status (0 success, 1 failure)
  195. /// @param exp_txt for success cases this defines the expected filename,
  196. /// for failure cases this defines the expected error message
  197. void checkConfigWrite(const std::string& response_txt, int exp_status,
  198. const std::string& exp_txt = "") {
  199. ConstElementPtr rsp;
  200. EXPECT_NO_THROW(rsp = Element::fromJSON(response_txt));
  201. ASSERT_TRUE(rsp);
  202. int status;
  203. ConstElementPtr params = parseAnswer(status, rsp);
  204. EXPECT_EQ(exp_status, status);
  205. if (exp_status == CONTROL_RESULT_SUCCESS) {
  206. // Let's check couple things...
  207. // The parameters must include filename
  208. ASSERT_TRUE(params);
  209. ASSERT_TRUE(params->get("filename"));
  210. ASSERT_EQ(Element::string, params->get("filename")->getType());
  211. EXPECT_EQ(exp_txt, params->get("filename")->stringValue());
  212. // The parameters must include size. And the size
  213. // must indicate some content.
  214. ASSERT_TRUE(params->get("size"));
  215. ASSERT_EQ(Element::integer, params->get("size")->getType());
  216. int64_t size = params->get("size")->intValue();
  217. EXPECT_LE(1, size);
  218. // Now check if the file is really there and suitable for
  219. // opening.
  220. ifstream f(exp_txt, ios::binary | ios::ate);
  221. ASSERT_TRUE(f.good());
  222. // Now check that it is the correct size as reported.
  223. EXPECT_EQ(size, static_cast<int64_t>(f.tellg()));
  224. // Finally, check that it's really a JSON.
  225. ElementPtr from_file = Element::fromJSONFile(exp_txt);
  226. ASSERT_TRUE(from_file);
  227. } else if (exp_status == CONTROL_RESULT_ERROR) {
  228. // Let's check if the reason for failure was given.
  229. ConstElementPtr text = rsp->get("text");
  230. ASSERT_TRUE(text);
  231. ASSERT_EQ(Element::string, text->getType());
  232. EXPECT_EQ(exp_txt, text->stringValue());
  233. } else {
  234. ADD_FAILURE() << "Invalid expected status: " << exp_status;
  235. }
  236. }
  237. };
  238. TEST_F(CtrlChannelDhcpv4SrvTest, commands) {
  239. ASSERT_NO_THROW(
  240. server_.reset(new NakedControlledDhcpv4Srv());
  241. );
  242. // Use empty parameters list
  243. ElementPtr params(new isc::data::MapElement());
  244. int rcode = -1;
  245. // Case 1: send bogus command
  246. ConstElementPtr result = ControlledDhcpv4Srv::processCommand("blah", params);
  247. ConstElementPtr comment = parseAnswer(rcode, result);
  248. EXPECT_EQ(1, rcode); // expect failure (no such command as blah)
  249. // Case 2: send shutdown command without any parameters
  250. result = ControlledDhcpv4Srv::processCommand("shutdown", params);
  251. comment = parseAnswer(rcode, result);
  252. EXPECT_EQ(0, rcode); // expect success
  253. const pid_t pid(getpid());
  254. ConstElementPtr x(new isc::data::IntElement(pid));
  255. params->set("pid", x);
  256. // Case 3: send shutdown command with 1 parameter: pid
  257. result = ControlledDhcpv4Srv::processCommand("shutdown", params);
  258. comment = parseAnswer(rcode, result);
  259. EXPECT_EQ(0, rcode); // expect success
  260. }
  261. // Check that the "libreload" command will reload libraries
  262. TEST_F(CtrlChannelDhcpv4SrvTest, libreload) {
  263. createUnixChannelServer();
  264. // Ensure no marker files to start with.
  265. ASSERT_FALSE(checkMarkerFileExists(LOAD_MARKER_FILE));
  266. ASSERT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));
  267. // Load two libraries
  268. HookLibsCollection libraries;
  269. libraries.push_back(make_pair(CALLOUT_LIBRARY_1, ConstElementPtr()));
  270. libraries.push_back(make_pair(CALLOUT_LIBRARY_2, ConstElementPtr()));
  271. HooksManager::loadLibraries(libraries);
  272. // Check they are loaded.
  273. std::vector<std::string> loaded_libraries =
  274. HooksManager::getLibraryNames();
  275. ASSERT_TRUE(extractNames(libraries) == loaded_libraries);
  276. // ... which also included checking that the marker file created by the
  277. // load functions exists and holds the correct value (of "12" - the
  278. // first library appends "1" to the file, the second appends "2"). Also
  279. // check that the unload marker file does not yet exist.
  280. EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "12"));
  281. EXPECT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));
  282. // Now execute the "libreload" command. This should cause the libraries
  283. // to unload and to reload.
  284. std::string response;
  285. sendUnixCommand("{ \"command\": \"libreload\" }", response);
  286. EXPECT_EQ("{ \"result\": 0, "
  287. "\"text\": \"Hooks libraries successfully reloaded.\" }"
  288. , response);
  289. // Check that the libraries have unloaded and reloaded. The libraries are
  290. // unloaded in the reverse order to which they are loaded. When they load,
  291. // they should append information to the loading marker file.
  292. EXPECT_TRUE(checkMarkerFile(UNLOAD_MARKER_FILE, "21"));
  293. EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "1212"));
  294. }
  295. // This test checks which commands are registered by the DHCPv4 server.
  296. TEST_F(CtrlChannelDhcpv4SrvTest, commandsRegistration) {
  297. ConstElementPtr list_cmds = createCommand("list-commands");
  298. ConstElementPtr answer;
  299. // By default the list should be empty (except the standard list-commands
  300. // supported by the CommandMgr itself)
  301. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  302. ASSERT_TRUE(answer);
  303. ASSERT_TRUE(answer->get("arguments"));
  304. EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
  305. // Created server should register several additional commands.
  306. ASSERT_NO_THROW(
  307. server_.reset(new NakedControlledDhcpv4Srv());
  308. );
  309. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  310. ASSERT_TRUE(answer);
  311. ASSERT_TRUE(answer->get("arguments"));
  312. std::string command_list = answer->get("arguments")->str();
  313. EXPECT_TRUE(command_list.find("\"list-commands\"") != string::npos);
  314. EXPECT_TRUE(command_list.find("\"build-report\"") != string::npos);
  315. EXPECT_TRUE(command_list.find("\"config-get\"") != string::npos);
  316. EXPECT_TRUE(command_list.find("\"config-set\"") != string::npos);
  317. EXPECT_TRUE(command_list.find("\"config-write\"") != string::npos);
  318. EXPECT_TRUE(command_list.find("\"leases-reclaim\"") != string::npos);
  319. EXPECT_TRUE(command_list.find("\"libreload\"") != string::npos);
  320. EXPECT_TRUE(command_list.find("\"shutdown\"") != string::npos);
  321. EXPECT_TRUE(command_list.find("\"statistic-get\"") != string::npos);
  322. EXPECT_TRUE(command_list.find("\"statistic-get-all\"") != string::npos);
  323. EXPECT_TRUE(command_list.find("\"statistic-remove\"") != string::npos);
  324. EXPECT_TRUE(command_list.find("\"statistic-remove-all\"") != string::npos);
  325. EXPECT_TRUE(command_list.find("\"statistic-reset\"") != string::npos);
  326. EXPECT_TRUE(command_list.find("\"statistic-reset-all\"") != string::npos);
  327. EXPECT_TRUE(command_list.find("\"version-get\"") != string::npos);
  328. // Ok, and now delete the server. It should deregister its commands.
  329. server_.reset();
  330. // The list should be (almost) empty again.
  331. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  332. ASSERT_TRUE(answer);
  333. ASSERT_TRUE(answer->get("arguments"));
  334. EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
  335. }
  336. // Tests that the server properly responds to invalid commands sent
  337. // via ControlChannel
  338. TEST_F(CtrlChannelDhcpv4SrvTest, controlChannelNegative) {
  339. createUnixChannelServer();
  340. std::string response;
  341. sendUnixCommand("{ \"command\": \"bogus\" }", response);
  342. EXPECT_EQ("{ \"result\": 2,"
  343. " \"text\": \"'bogus' command not supported.\" }", response);
  344. sendUnixCommand("utter nonsense", response);
  345. EXPECT_EQ("{ \"result\": 1, "
  346. "\"text\": \"error: unexpected character u in <string>:1:2\" }",
  347. response);
  348. }
  349. // Tests that the server properly responds to shtudown command sent
  350. // via ControlChannel
  351. TEST_F(CtrlChannelDhcpv4SrvTest, controlChannelShutdown) {
  352. createUnixChannelServer();
  353. std::string response;
  354. sendUnixCommand("{ \"command\": \"shutdown\" }", response);
  355. EXPECT_EQ("{ \"result\": 0, \"text\": \"Shutting down.\" }",response);
  356. }
  357. // This test verifies that the DHCP server immediately reclaims expired
  358. // leases on leases-reclaim command
  359. TEST_F(CtrlChannelDhcpv4SrvTest, controlLeasesReclaim) {
  360. createUnixChannelServer();
  361. // Create expired leases. Leases are expired by 40 seconds ago
  362. // (valid lifetime = 60, cltt = now - 100).
  363. HWAddrPtr hwaddr0(new HWAddr(HWAddr::fromText("00:01:02:03:04:05")));
  364. Lease4Ptr lease0(new Lease4(IOAddress("10.0.0.1"), hwaddr0,
  365. ClientIdPtr(), 60, 10, 20,
  366. time(NULL) - 100, SubnetID(1)));
  367. HWAddrPtr hwaddr1(new HWAddr(HWAddr::fromText("01:02:03:04:05:06")));
  368. Lease4Ptr lease1(new Lease4(IOAddress("10.0.0.2"), hwaddr1,
  369. ClientIdPtr(), 60, 10, 20,
  370. time(NULL) - 100, SubnetID(1)));
  371. // Add leases to the database.
  372. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  373. ASSERT_NO_THROW(lease_mgr.addLease(lease0));
  374. ASSERT_NO_THROW(lease_mgr.addLease(lease1));
  375. // Make sure they have been added.
  376. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.1")));
  377. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.2")));
  378. // No arguments
  379. std::string response;
  380. sendUnixCommand("{ \"command\": \"leases-reclaim\" }", response);
  381. EXPECT_EQ("{ \"result\": 1, \"text\": "
  382. "\"Missing mandatory 'remove' parameter.\" }", response);
  383. // Bad argument name
  384. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  385. "\"arguments\": { \"reclaim\": true } }", response);
  386. EXPECT_EQ("{ \"result\": 1, \"text\": "
  387. "\"Missing mandatory 'remove' parameter.\" }", response);
  388. // Bad remove argument type
  389. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  390. "\"arguments\": { \"remove\": \"bogus\" } }", response);
  391. EXPECT_EQ("{ \"result\": 1, \"text\": "
  392. "\"'remove' parameter expected to be a boolean.\" }", response);
  393. // Send the command
  394. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  395. "\"arguments\": { \"remove\": false } }", response);
  396. EXPECT_EQ("{ \"result\": 0, \"text\": "
  397. "\"Reclamation of expired leases is complete.\" }", response);
  398. // Leases should be reclaimed, but not removed
  399. ASSERT_NO_THROW(lease0 = lease_mgr.getLease4(IOAddress("10.0.0.1")));
  400. ASSERT_NO_THROW(lease1 = lease_mgr.getLease4(IOAddress("10.0.0.2")));
  401. ASSERT_TRUE(lease0);
  402. ASSERT_TRUE(lease1);
  403. EXPECT_TRUE(lease0->stateExpiredReclaimed());
  404. EXPECT_TRUE(lease1->stateExpiredReclaimed());
  405. }
  406. // This test verifies that the DHCP server handles version-get commands
  407. TEST_F(CtrlChannelDhcpv4SrvTest, getversion) {
  408. createUnixChannelServer();
  409. std::string response;
  410. // Send the version-get command
  411. sendUnixCommand("{ \"command\": \"version-get\" }", response);
  412. EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
  413. EXPECT_TRUE(response.find("log4cplus") != string::npos);
  414. EXPECT_FALSE(response.find("GTEST_VERSION") != string::npos);
  415. // Send the build-report command
  416. sendUnixCommand("{ \"command\": \"build-report\" }", response);
  417. EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
  418. EXPECT_TRUE(response.find("GTEST_VERSION") != string::npos);
  419. }
  420. // This test verifies that the DHCP server immediately removed expired
  421. // This test verifies that the DHCP server immediately removed expired
  422. // leases on leases-reclaim command with remove = true
  423. TEST_F(CtrlChannelDhcpv4SrvTest, controlLeasesReclaimRemove) {
  424. createUnixChannelServer();
  425. // Create expired leases. Leases are expired by 40 seconds ago
  426. // (valid lifetime = 60, cltt = now - 100).
  427. HWAddrPtr hwaddr0(new HWAddr(HWAddr::fromText("00:01:02:03:04:05")));
  428. Lease4Ptr lease0(new Lease4(IOAddress("10.0.0.1"), hwaddr0,
  429. ClientIdPtr(), 60, 10, 20,
  430. time(NULL) - 100, SubnetID(1)));
  431. HWAddrPtr hwaddr1(new HWAddr(HWAddr::fromText("01:02:03:04:05:06")));
  432. Lease4Ptr lease1(new Lease4(IOAddress("10.0.0.2"), hwaddr1,
  433. ClientIdPtr(), 60, 10, 20,
  434. time(NULL) - 100, SubnetID(1)));
  435. // Add leases to the database.
  436. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  437. ASSERT_NO_THROW(lease_mgr.addLease(lease0));
  438. ASSERT_NO_THROW(lease_mgr.addLease(lease1));
  439. // Make sure they have been added.
  440. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.1")));
  441. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.2")));
  442. // Send the command
  443. std::string response;
  444. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  445. "\"arguments\": { \"remove\": true } }", response);
  446. EXPECT_EQ("{ \"result\": 0, \"text\": "
  447. "\"Reclamation of expired leases is complete.\" }", response);
  448. // Leases should have been removed.
  449. ASSERT_NO_THROW(lease0 = lease_mgr.getLease4(IOAddress("10.0.0.1")));
  450. ASSERT_NO_THROW(lease1 = lease_mgr.getLease4(IOAddress("10.0.0.2")));
  451. EXPECT_FALSE(lease0);
  452. EXPECT_FALSE(lease1);
  453. }
  454. // Tests that the server properly responds to statistics commands. Note this
  455. // is really only intended to verify that the appropriate Statistics handler
  456. // is called based on the command. It is not intended to be an exhaustive
  457. // test of Dhcpv4 statistics.
  458. TEST_F(CtrlChannelDhcpv4SrvTest, controlChannelStats) {
  459. createUnixChannelServer();
  460. std::string response;
  461. // Check statistic-get
  462. sendUnixCommand("{ \"command\" : \"statistic-get\", "
  463. " \"arguments\": {"
  464. " \"name\":\"bogus\" }}", response);
  465. EXPECT_EQ("{ \"arguments\": { }, \"result\": 0 }", response);
  466. // Check statistic-get-all
  467. sendUnixCommand("{ \"command\" : \"statistic-get-all\", "
  468. " \"arguments\": {}}", response);
  469. EXPECT_EQ("{ \"arguments\": { }, \"result\": 0 }", response);
  470. // Check statistic-reset
  471. sendUnixCommand("{ \"command\" : \"statistic-reset\", "
  472. " \"arguments\": {"
  473. " \"name\":\"bogus\" }}", response);
  474. EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
  475. response);
  476. // Check statistic-reset-all
  477. sendUnixCommand("{ \"command\" : \"statistic-reset-all\", "
  478. " \"arguments\": {}}", response);
  479. EXPECT_EQ("{ \"result\": 0, \"text\": "
  480. "\"All statistics reset to neutral values.\" }", response);
  481. // Check statistic-remove
  482. sendUnixCommand("{ \"command\" : \"statistic-remove\", "
  483. " \"arguments\": {"
  484. " \"name\":\"bogus\" }}", response);
  485. EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
  486. response);
  487. // Check statistic-remove-all
  488. sendUnixCommand("{ \"command\" : \"statistic-remove-all\", "
  489. " \"arguments\": {}}", response);
  490. EXPECT_EQ("{ \"result\": 0, \"text\": \"All statistics removed.\" }",
  491. response);
  492. }
  493. // Check that the "config-set" command will replace current configuration
  494. TEST_F(CtrlChannelDhcpv4SrvTest, configSet) {
  495. createUnixChannelServer();
  496. // Define strings to permutate the config arguments
  497. // (Note the line feeds makes errors easy to find)
  498. string set_config_txt = "{ \"command\": \"config-set\" \n";
  499. string args_txt = " \"arguments\": { \n";
  500. string dhcp4_cfg_txt =
  501. " \"Dhcp4\": { \n"
  502. " \"interfaces-config\": { \n"
  503. " \"interfaces\": [\"*\"] \n"
  504. " }, \n"
  505. " \"valid-lifetime\": 4000, \n"
  506. " \"renew-timer\": 1000, \n"
  507. " \"rebind-timer\": 2000, \n"
  508. " \"lease-database\": { \n"
  509. " \"type\": \"memfile\", \n"
  510. " \"persist\":false, \n"
  511. " \"lfc-interval\": 0 \n"
  512. " }, \n"
  513. " \"expired-leases-processing\": { \n"
  514. " \"reclaim-timer-wait-time\": 0, \n"
  515. " \"hold-reclaimed-time\": 0, \n"
  516. " \"flush-reclaimed-timer-wait-time\": 0 \n"
  517. " },"
  518. " \"subnet4\": [ \n";
  519. string subnet1 =
  520. " {\"subnet\": \"192.2.0.0/24\", \n"
  521. " \"pools\": [{ \"pool\": \"192.2.0.1-192.2.0.50\" }]}\n";
  522. string subnet2 =
  523. " {\"subnet\": \"192.2.1.0/24\", \n"
  524. " \"pools\": [{ \"pool\": \"192.2.1.1-192.2.1.50\" }]}\n";
  525. string bad_subnet =
  526. " {\"BOGUS\": \"192.2.2.0/24\", \n"
  527. " \"pools\": [{ \"pool\": \"192.2.2.1-192.2.2.50\" }]}\n";
  528. string subnet_footer =
  529. " ] \n";
  530. string control_socket_header =
  531. " ,\"control-socket\": { \n"
  532. " \"socket-type\": \"unix\", \n"
  533. " \"socket-name\": \"";
  534. string control_socket_footer =
  535. "\" \n} \n";
  536. string logger_txt =
  537. " \"Logging\": { \n"
  538. " \"loggers\": [ { \n"
  539. " \"name\": \"kea\", \n"
  540. " \"severity\": \"FATAL\", \n"
  541. " \"output_options\": [{ \n"
  542. " \"output\": \"/dev/null\" \n"
  543. " }] \n"
  544. " }] \n"
  545. " } \n";
  546. std::ostringstream os;
  547. // Create a valid config with all the parts should parse
  548. os << set_config_txt << ","
  549. << args_txt
  550. << dhcp4_cfg_txt
  551. << subnet1
  552. << subnet_footer
  553. << control_socket_header
  554. << socket_path_
  555. << control_socket_footer
  556. << "}\n" // close dhcp4
  557. << ","
  558. << logger_txt
  559. << "}}";
  560. // Send the config-set command
  561. std::string response;
  562. sendUnixCommand(os.str(), response);
  563. // Verify the configuration was successful.
  564. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
  565. response);
  566. // Check that the config was indeed applied.
  567. const Subnet4Collection* subnets =
  568. CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  569. EXPECT_EQ(1, subnets->size());
  570. // Create a config with malformed subnet that should fail to parse.
  571. os.str("");
  572. os << set_config_txt << ","
  573. << args_txt
  574. << dhcp4_cfg_txt
  575. << bad_subnet
  576. << subnet_footer
  577. << control_socket_header
  578. << socket_path_
  579. << control_socket_footer
  580. << "}\n" // close dhcp4
  581. "}}";
  582. // Send the config-set command
  583. sendUnixCommand(os.str(), response);
  584. // Should fail with a syntax error
  585. EXPECT_EQ("{ \"result\": 1, "
  586. "\"text\": \"subnet configuration failed: mandatory 'subnet' "
  587. "parameter is missing for a subnet being configured (<string>:20:17)\" }",
  588. response);
  589. // Check that the config was not lost
  590. subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  591. EXPECT_EQ(1, subnets->size());
  592. // Create a valid config with two subnets and no command channel.
  593. // It should succeed, client should still receive the response
  594. os.str("");
  595. os << set_config_txt << ","
  596. << args_txt
  597. << dhcp4_cfg_txt
  598. << subnet1
  599. << ",\n"
  600. << subnet2
  601. << subnet_footer
  602. << "}\n" // close dhcp4
  603. << "}}";
  604. // Verify the control channel socket exists.
  605. ASSERT_TRUE(fileExists(socket_path_));
  606. // Send the config-set command.
  607. sendUnixCommand(os.str(), response);
  608. // Verify the control channel socket no longer exists.
  609. EXPECT_FALSE(fileExists(socket_path_));
  610. // With no command channel, should still receive the response.
  611. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
  612. response);
  613. // Check that the config was not lost
  614. subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  615. EXPECT_EQ(2, subnets->size());
  616. // Clean up after the test.
  617. CfgMgr::instance().clear();
  618. }
  619. // Tests that the server properly responds to shtudown command sent
  620. // via ControlChannel
  621. TEST_F(CtrlChannelDhcpv4SrvTest, listCommands) {
  622. createUnixChannelServer();
  623. std::string response;
  624. sendUnixCommand("{ \"command\": \"list-commands\" }", response);
  625. ConstElementPtr rsp;
  626. EXPECT_NO_THROW(rsp = Element::fromJSON(response));
  627. // We expect the server to report at least the following commands:
  628. checkListCommands(rsp, "build-report");
  629. checkListCommands(rsp, "config-get");
  630. checkListCommands(rsp, "config-reload");
  631. checkListCommands(rsp, "config-set");
  632. checkListCommands(rsp, "config-write");
  633. checkListCommands(rsp, "list-commands");
  634. checkListCommands(rsp, "leases-reclaim");
  635. checkListCommands(rsp, "libreload");
  636. checkListCommands(rsp, "shutdown");
  637. checkListCommands(rsp, "statistic-get");
  638. checkListCommands(rsp, "statistic-get-all");
  639. checkListCommands(rsp, "statistic-remove");
  640. checkListCommands(rsp, "statistic-remove-all");
  641. checkListCommands(rsp, "statistic-reset");
  642. checkListCommands(rsp, "statistic-reset-all");
  643. checkListCommands(rsp, "version-get");
  644. }
  645. // Tests if the server returns its configuration using config-get.
  646. // Note there are separate tests that verify if toElement() called by the
  647. // config-get handler are actually converting the configuration correctly.
  648. TEST_F(CtrlChannelDhcpv4SrvTest, configGet) {
  649. createUnixChannelServer();
  650. std::string response;
  651. sendUnixCommand("{ \"command\": \"config-get\" }", response);
  652. ConstElementPtr rsp;
  653. // The response should be a valid JSON.
  654. EXPECT_NO_THROW(rsp = Element::fromJSON(response));
  655. ASSERT_TRUE(rsp);
  656. int status;
  657. ConstElementPtr cfg = parseAnswer(status, rsp);
  658. EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
  659. // Ok, now roughly check if the response seems legit.
  660. ASSERT_TRUE(cfg);
  661. ASSERT_EQ(Element::map, cfg->getType());
  662. EXPECT_TRUE(cfg->get("Dhcp4"));
  663. }
  664. // Verify that the "config-test" command will do what we expect.
  665. TEST_F(CtrlChannelDhcpv4SrvTest, configTest) {
  666. createUnixChannelServer();
  667. // Define strings to permutate the config arguments
  668. // (Note the line feeds makes errors easy to find)
  669. string set_config_txt = "{ \"command\": \"config-set\" \n";
  670. string config_test_txt = "{ \"command\": \"config-test\" \n";
  671. string args_txt = " \"arguments\": { \n";
  672. string dhcp4_cfg_txt =
  673. " \"Dhcp4\": { \n"
  674. " \"interfaces-config\": { \n"
  675. " \"interfaces\": [\"*\"] \n"
  676. " }, \n"
  677. " \"valid-lifetime\": 4000, \n"
  678. " \"renew-timer\": 1000, \n"
  679. " \"rebind-timer\": 2000, \n"
  680. " \"lease-database\": { \n"
  681. " \"type\": \"memfile\", \n"
  682. " \"persist\":false, \n"
  683. " \"lfc-interval\": 0 \n"
  684. " }, \n"
  685. " \"expired-leases-processing\": { \n"
  686. " \"reclaim-timer-wait-time\": 0, \n"
  687. " \"hold-reclaimed-time\": 0, \n"
  688. " \"flush-reclaimed-timer-wait-time\": 0 \n"
  689. " },"
  690. " \"subnet4\": [ \n";
  691. string subnet1 =
  692. " {\"subnet\": \"192.2.0.0/24\", \n"
  693. " \"pools\": [{ \"pool\": \"192.2.0.1-192.2.0.50\" }]}\n";
  694. string subnet2 =
  695. " {\"subnet\": \"192.2.1.0/24\", \n"
  696. " \"pools\": [{ \"pool\": \"192.2.1.1-192.2.1.50\" }]}\n";
  697. string bad_subnet =
  698. " {\"BOGUS\": \"192.2.2.0/24\", \n"
  699. " \"pools\": [{ \"pool\": \"192.2.2.1-192.2.2.50\" }]}\n";
  700. string subnet_footer =
  701. " ] \n";
  702. string control_socket_header =
  703. " ,\"control-socket\": { \n"
  704. " \"socket-type\": \"unix\", \n"
  705. " \"socket-name\": \"";
  706. string control_socket_footer =
  707. "\" \n} \n";
  708. string logger_txt =
  709. " \"Logging\": { \n"
  710. " \"loggers\": [ { \n"
  711. " \"name\": \"kea\", \n"
  712. " \"severity\": \"FATAL\", \n"
  713. " \"output_options\": [{ \n"
  714. " \"output\": \"/dev/null\" \n"
  715. " }] \n"
  716. " }] \n"
  717. " } \n";
  718. std::ostringstream os;
  719. // Create a valid config with all the parts should parse
  720. os << set_config_txt << ","
  721. << args_txt
  722. << dhcp4_cfg_txt
  723. << subnet1
  724. << subnet_footer
  725. << control_socket_header
  726. << socket_path_
  727. << control_socket_footer
  728. << "}\n" // close dhcp4
  729. << ","
  730. << logger_txt
  731. << "}}";
  732. // Send the config-set command
  733. std::string response;
  734. sendUnixCommand(os.str(), response);
  735. // Verify the configuration was successful.
  736. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
  737. response);
  738. // Check that the config was indeed applied.
  739. const Subnet4Collection* subnets =
  740. CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  741. EXPECT_EQ(1, subnets->size());
  742. // Create a config with malformed subnet that should fail to parse.
  743. os.str("");
  744. os << config_test_txt << ","
  745. << args_txt
  746. << dhcp4_cfg_txt
  747. << bad_subnet
  748. << subnet_footer
  749. << control_socket_header
  750. << socket_path_
  751. << control_socket_footer
  752. << "}\n" // close dhcp4
  753. "}}";
  754. // Send the config-test command
  755. sendUnixCommand(os.str(), response);
  756. // Should fail with a syntax error
  757. EXPECT_EQ("{ \"result\": 1, "
  758. "\"text\": \"subnet configuration failed: mandatory 'subnet' "
  759. "parameter is missing for a subnet being configured (<string>:20:17)\" }",
  760. response);
  761. // Check that the config was not lost
  762. subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  763. EXPECT_EQ(1, subnets->size());
  764. // Create a valid config with two subnets and no command channel.
  765. os.str("");
  766. os << config_test_txt << ","
  767. << args_txt
  768. << dhcp4_cfg_txt
  769. << subnet1
  770. << ",\n"
  771. << subnet2
  772. << subnet_footer
  773. << "}\n" // close dhcp4
  774. << "}}";
  775. // Verify the control channel socket exists.
  776. ASSERT_TRUE(fileExists(socket_path_));
  777. // Send the config-test command
  778. sendUnixCommand(os.str(), response);
  779. // Verify the control channel socket still exists.
  780. EXPECT_TRUE(fileExists(socket_path_));
  781. // Verify the configuration was successful.
  782. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration seems sane. "
  783. "Control-socket, hook-libraries, and D2 configuration were "
  784. "sanity checked, but not applied.\" }",
  785. response);
  786. // Check that the config was not applied
  787. subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  788. EXPECT_EQ(1, subnets->size());
  789. // Clean up after the test.
  790. CfgMgr::instance().clear();
  791. }
  792. // Tests if config-write can be called without any parameters.
  793. TEST_F(CtrlChannelDhcpv4SrvTest, writeConfigNoFilename) {
  794. createUnixChannelServer();
  795. std::string response;
  796. // This is normally set by the command line -c parameter.
  797. server_->setConfigFile("test1.json");
  798. // If the filename is not explicitly specified, the name used
  799. // in -c command line switch is used.
  800. sendUnixCommand("{ \"command\": \"config-write\" }", response);
  801. checkConfigWrite(response, CONTROL_RESULT_SUCCESS, "test1.json");
  802. ::remove("test1.json");
  803. }
  804. // Tests if config-write can be called with a valid filename as parameter.
  805. TEST_F(CtrlChannelDhcpv4SrvTest, writeConfigFilename) {
  806. createUnixChannelServer();
  807. std::string response;
  808. sendUnixCommand("{ \"command\": \"config-write\", "
  809. "\"arguments\": { \"filename\": \"test2.json\" } }", response);
  810. checkConfigWrite(response, CONTROL_RESULT_SUCCESS, "test2.json");
  811. ::remove("test2.json");
  812. }
  813. // Tests if config-write rejects invalid filename (a one that tries to escape
  814. // the current directory).
  815. TEST_F(CtrlChannelDhcpv4SrvTest, writeConfigInvalidJailEscape) {
  816. createUnixChannelServer();
  817. std::string response;
  818. sendUnixCommand("{ \"command\": \"config-write\", \"arguments\": "
  819. "{ \"filename\": \"../test3.json\" } }", response);
  820. checkConfigWrite(response, CONTROL_RESULT_ERROR,
  821. "Using '..' in filename is not allowed.");
  822. }
  823. // Tests if config-write rejects invalid filename (absolute paths are not allowed)
  824. TEST_F(CtrlChannelDhcpv4SrvTest, writeConfigInvalidAbsPath) {
  825. createUnixChannelServer();
  826. std::string response;
  827. sendUnixCommand("{ \"command\": \"config-write\", \"arguments\": "
  828. "{ \"filename\": \"/tmp/test4.json\" } }", response);
  829. checkConfigWrite(response, CONTROL_RESULT_ERROR,
  830. "Absolute path in filename is not allowed.");
  831. }
  832. // Tests if config-write rejects invalid filename (one with backslashes, which may
  833. // lead to some other tricks)
  834. TEST_F(CtrlChannelDhcpv4SrvTest, writeConfigInvalidEscape) {
  835. createUnixChannelServer();
  836. std::string response;
  837. // This will be converted to foo(single backslash)test5.json
  838. sendUnixCommand("{ \"command\": \"config-write\", \"arguments\": "
  839. "{ \"filename\": \"foo\\\\test5.json\" } }", response);
  840. checkConfigWrite(response, CONTROL_RESULT_ERROR,
  841. "Using \\ in filename is not allowed.");
  842. }
  843. // Tests if config-reload attempts to reload a file and reports that the
  844. // file is missing.
  845. TEST_F(CtrlChannelDhcpv4SrvTest, configReloadMissingFile) {
  846. createUnixChannelServer();
  847. std::string response;
  848. // This is normally set to whatever value is passed to -c when the server is
  849. // started, but we're not starting it that way, so need to set it by hand.
  850. server_->setConfigFile("test6.json");
  851. // Tell the server to reload its configuration. It should attempt to load
  852. // test6.json (and fail, because the file is not there).
  853. sendUnixCommand("{ \"command\": \"config-reload\" }", response);
  854. // Verify the reload was rejected.
  855. EXPECT_EQ("{ \"result\": 1, \"text\": \"Config reload failed:"
  856. "configuration error using file 'test6.json': Unable to open file "
  857. "test6.json\" }",
  858. response);
  859. }
  860. // Tests if config-reload attempts to reload a file and reports that the
  861. // file is not a valid JSON.
  862. TEST_F(CtrlChannelDhcpv4SrvTest, configReloadBrokenFile) {
  863. createUnixChannelServer();
  864. std::string response;
  865. // This is normally set to whatever value is passed to -c when the server is
  866. // started, but we're not starting it that way, so need to set it by hand.
  867. server_->setConfigFile("test7.json");
  868. // Although Kea is smart, its AI routines are not smart enough to handle
  869. // this one... at least not yet.
  870. ofstream f("test7.json", ios::trunc);
  871. f << "gimme some addrs, bro!";
  872. f.close();
  873. // Now tell Kea to reload its config.
  874. sendUnixCommand("{ \"command\": \"config-reload\" }", response);
  875. // Verify the reload will fail.
  876. EXPECT_EQ("{ \"result\": 1, \"text\": \"Config reload failed:"
  877. "configuration error using file 'test7.json': "
  878. "test7.json:1.1: Invalid character: g\" }",
  879. response);
  880. ::remove("test7.json");
  881. }
  882. // Tests if config-reload attempts to reload a file and reports that the
  883. // file is loaded correctly.
  884. TEST_F(CtrlChannelDhcpv4SrvTest, configReloadValid) {
  885. createUnixChannelServer();
  886. std::string response;
  887. // This is normally set to whatever value is passed to -c when the server is
  888. // started, but we're not starting it that way, so need to set it by hand.
  889. server_->setConfigFile("test8.json");
  890. // Ok, enough fooling around. Let's create a valid config.
  891. const std::string cfg_txt =
  892. "{ \"Dhcp4\": {"
  893. " \"interfaces-config\": {"
  894. " \"interfaces\": [ \"*\" ]"
  895. " },"
  896. " \"subnet4\": ["
  897. " { \"subnet\": \"192.0.2.0/24\" },"
  898. " { \"subnet\": \"192.0.3.0/24\" }"
  899. " ],"
  900. " \"valid-lifetime\": 4000,"
  901. " \"lease-database\": {"
  902. " \"type\": \"memfile\", \"persist\": false }"
  903. "} }";
  904. ofstream f("test8.json", ios::trunc);
  905. f << cfg_txt;
  906. f.close();
  907. // This command should reload test8.json config.
  908. sendUnixCommand("{ \"command\": \"config-reload\" }", response);
  909. // Verify the configuration was successful.
  910. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
  911. response);
  912. // Check that the config was indeed applied.
  913. const Subnet4Collection* subnets =
  914. CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  915. EXPECT_EQ(2, subnets->size());
  916. ::remove("test8.json");
  917. }
  918. } // End of anonymous namespace