ctrl_dhcp6_srv_unittest.cc 40 KB

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