ctrl_dhcp4_srv_unittest.cc 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  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/interval_timer.h>
  8. #include <asiolink/io_service.h>
  9. #include <cc/command_interpreter.h>
  10. #include <config/command_mgr.h>
  11. #include <dhcp/dhcp4.h>
  12. #include <dhcp4/ctrl_dhcp4_srv.h>
  13. #include <dhcp4/tests/dhcp4_test_utils.h>
  14. #include <dhcpsrv/cfgmgr.h>
  15. #include <dhcpsrv/lease.h>
  16. #include <dhcpsrv/lease_mgr_factory.h>
  17. #include <hooks/hooks_manager.h>
  18. #include <log/logger_support.h>
  19. #include <stats/stats_mgr.h>
  20. #include <testutils/io_utils.h>
  21. #include <testutils/unix_control_client.h>
  22. #include "marker_file.h"
  23. #include "test_libraries.h"
  24. #include <boost/scoped_ptr.hpp>
  25. #include <gtest/gtest.h>
  26. #include <fstream>
  27. #include <iostream>
  28. #include <sstream>
  29. #include <thread>
  30. #include <arpa/inet.h>
  31. #include <unistd.h>
  32. using namespace std;
  33. using namespace isc;
  34. using namespace isc::asiolink;
  35. using namespace isc::config;
  36. using namespace isc::data;
  37. using namespace isc::dhcp;
  38. using namespace isc::dhcp::test;
  39. using namespace isc::hooks;
  40. using namespace isc::stats;
  41. using namespace isc::test;
  42. namespace {
  43. /// @brief Simple RAII class which stops IO service upon destruction
  44. /// of the object.
  45. class IOServiceWork {
  46. public:
  47. /// @brief Constructor.
  48. ///
  49. /// @param io_service Pointer to the IO service to be stopped.
  50. IOServiceWork(const IOServicePtr& io_service)
  51. : io_service_(io_service) {
  52. }
  53. /// @brief Destructor.
  54. ///
  55. /// Stops IO service.
  56. ~IOServiceWork() {
  57. io_service_->stop();
  58. }
  59. private:
  60. /// @brief Pointer to the IO service to be stopped upon destruction.
  61. IOServicePtr io_service_;
  62. };
  63. class NakedControlledDhcpv4Srv: public ControlledDhcpv4Srv {
  64. // "Naked" DHCPv4 server, exposes internal fields
  65. public:
  66. NakedControlledDhcpv4Srv():ControlledDhcpv4Srv(0) { }
  67. /// Expose internal methods for the sake of testing
  68. using Dhcpv4Srv::receivePacket;
  69. };
  70. /// @brief Fixture class intended for testin control channel in the DHCPv4Srv
  71. class CtrlChannelDhcpv4SrvTest : public ::testing::Test {
  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<NakedControlledDhcpv4Srv> server_;
  77. /// @brief Default constructor
  78. ///
  79. /// Sets socket path to its default value.
  80. CtrlChannelDhcpv4SrvTest() {
  81. const char* env = getenv("KEA_SOCKET_TEST_DIR");
  82. if (env) {
  83. socket_path_ = string(env) + "/kea4.sock";
  84. } else {
  85. socket_path_ = string(TEST_DATA_BUILDDIR) + "/kea4.sock";
  86. }
  87. reset();
  88. }
  89. /// @brief Destructor
  90. ~CtrlChannelDhcpv4SrvTest() {
  91. LeaseMgrFactory::destroy();
  92. StatsMgr::instance().removeAll();
  93. CommandMgr::instance().closeCommandSocket();
  94. CommandMgr::instance().deregisterAll();
  95. server_.reset();
  96. };
  97. /// @brief Returns pointer to the server's IO service.
  98. ///
  99. /// @return Pointer to the server's IO service or null pointer if the server
  100. /// hasn't been created.
  101. IOServicePtr getIOService() {
  102. return (server_ ? server_->getIOService() : IOServicePtr());
  103. }
  104. void createUnixChannelServer() {
  105. ::remove(socket_path_.c_str());
  106. // Just a simple config. The important part here is the socket
  107. // location information.
  108. std::string header =
  109. "{"
  110. " \"interfaces-config\": {"
  111. " \"interfaces\": [ \"*\" ]"
  112. " },"
  113. " \"expired-leases-processing\": {"
  114. " \"reclaim-timer-wait-time\": 60,"
  115. " \"hold-reclaimed-time\": 500,"
  116. " \"flush-reclaimed-timer-wait-time\": 60"
  117. " },"
  118. " \"rebind-timer\": 2000, "
  119. " \"renew-timer\": 1000, "
  120. " \"subnet4\": [ ],"
  121. " \"valid-lifetime\": 4000,"
  122. " \"control-socket\": {"
  123. " \"socket-type\": \"unix\","
  124. " \"socket-name\": \"";
  125. std::string footer =
  126. "\" },"
  127. " \"lease-database\": {"
  128. " \"type\": \"memfile\", \"persist\": false }"
  129. "}";
  130. // Fill in the socket-name value with socket_path_ to
  131. // make the actual configuration text.
  132. std::string config_txt = header + socket_path_ + footer;
  133. ASSERT_NO_THROW(server_.reset(new NakedControlledDhcpv4Srv()));
  134. ConstElementPtr config;
  135. ASSERT_NO_THROW(config = parseDHCP4(config_txt));
  136. ConstElementPtr answer = server_->processConfig(config);
  137. // Commit the configuration so any subsequent reconfigurations
  138. // will only close the command channel if its configuration has
  139. // changed.
  140. CfgMgr::instance().commit();
  141. ASSERT_TRUE(answer);
  142. int status = 0;
  143. ConstElementPtr txt = isc::config::parseAnswer(status, answer);
  144. // This should succeed. If not, print the error message.
  145. ASSERT_EQ(0, status) << txt->str();
  146. // Now check that the socket was indeed open.
  147. ASSERT_GT(isc::config::CommandMgr::instance().getControlSocketFD(), -1);
  148. }
  149. /// @brief Reset hooks data
  150. ///
  151. /// Resets the data for the hooks-related portion of the test by ensuring
  152. /// that no libraries are loaded and that any marker files are deleted.
  153. void reset() {
  154. // Unload any previously-loaded libraries.
  155. HooksManager::unloadLibraries();
  156. // Get rid of any marker files.
  157. static_cast<void>(remove(LOAD_MARKER_FILE));
  158. static_cast<void>(remove(UNLOAD_MARKER_FILE));
  159. IfaceMgr::instance().deleteAllExternalSockets();
  160. CfgMgr::instance().clear();
  161. // Remove unix socket file
  162. ::remove(socket_path_.c_str());
  163. }
  164. /// @brief Conducts a command/response exchange via UnixCommandSocket
  165. ///
  166. /// This method connects to the given server over the given socket path.
  167. /// If successful, it then sends the given command and retrieves the
  168. /// server's response. Note that it calls the server's receivePacket()
  169. /// method where needed to cause the server to process IO events on
  170. /// control channel the control channel sockets.
  171. ///
  172. /// @param command the command text to execute in JSON form
  173. /// @param response variable into which the received response should be
  174. /// placed.
  175. void sendUnixCommand(const std::string& command, std::string& response) {
  176. response = "";
  177. boost::scoped_ptr<UnixControlClient> client;
  178. client.reset(new UnixControlClient());
  179. ASSERT_TRUE(client);
  180. // Connect to the server. This is expected to trigger server's acceptor
  181. // handler when IOService::poll() is run.
  182. ASSERT_TRUE(client->connectToServer(socket_path_));
  183. ASSERT_NO_THROW(getIOService()->poll());
  184. // Send the command. This will trigger server's handler which receives
  185. // data over the unix domain socket. The server will start sending
  186. // response to the client.
  187. ASSERT_TRUE(client->sendCommand(command));
  188. ASSERT_NO_THROW(getIOService()->poll());
  189. // Read the response generated by the server. Note that getResponse
  190. // only fails if there an IO error or no response data was present.
  191. // It is not based on the response content.
  192. ASSERT_TRUE(client->getResponse(response));
  193. // Now disconnect and process the close event
  194. client->disconnectFromServer();
  195. ASSERT_NO_THROW(getIOService()->poll());
  196. }
  197. /// @brief Checks response for list-commands
  198. ///
  199. /// This method checks if the list-commands response is generally sane
  200. /// and whether specified command is mentioned in the response.
  201. ///
  202. /// @param rsp response sent back by the server
  203. /// @param command command expected to be on the list.
  204. void checkListCommands(const ConstElementPtr& rsp, const std::string& command) {
  205. ConstElementPtr params;
  206. int status_code = -1;
  207. EXPECT_NO_THROW(params = parseAnswer(status_code, rsp));
  208. EXPECT_EQ(CONTROL_RESULT_SUCCESS, status_code);
  209. ASSERT_TRUE(params);
  210. ASSERT_EQ(Element::list, params->getType());
  211. int cnt = 0;
  212. for (size_t i = 0; i < params->size(); ++i) {
  213. string tmp = params->get(i)->stringValue();
  214. if (tmp == command) {
  215. // Command found, but that's not enough. Need to continue working
  216. // through the list to see if there are no duplicates.
  217. cnt++;
  218. }
  219. }
  220. // Exactly one command on the list is expected.
  221. EXPECT_EQ(1, cnt) << "Command " << command << " not found";
  222. }
  223. /// @brief Check if the answer for write-config command is correct
  224. ///
  225. /// @param response_txt response in text form (as read from the control socket)
  226. /// @param exp_status expected status (0 success, 1 failure)
  227. /// @param exp_txt for success cases this defines the expected filename,
  228. /// for failure cases this defines the expected error message
  229. void checkConfigWrite(const std::string& response_txt, int exp_status,
  230. const std::string& exp_txt = "") {
  231. ConstElementPtr rsp;
  232. EXPECT_NO_THROW(rsp = Element::fromJSON(response_txt));
  233. ASSERT_TRUE(rsp);
  234. int status;
  235. ConstElementPtr params = parseAnswer(status, rsp);
  236. EXPECT_EQ(exp_status, status);
  237. if (exp_status == CONTROL_RESULT_SUCCESS) {
  238. // Let's check couple things...
  239. // The parameters must include filename
  240. ASSERT_TRUE(params);
  241. ASSERT_TRUE(params->get("filename"));
  242. ASSERT_EQ(Element::string, params->get("filename")->getType());
  243. EXPECT_EQ(exp_txt, params->get("filename")->stringValue());
  244. // The parameters must include size. And the size
  245. // must indicate some content.
  246. ASSERT_TRUE(params->get("size"));
  247. ASSERT_EQ(Element::integer, params->get("size")->getType());
  248. int64_t size = params->get("size")->intValue();
  249. EXPECT_LE(1, size);
  250. // Now check if the file is really there and suitable for
  251. // opening.
  252. ifstream f(exp_txt, ios::binary | ios::ate);
  253. ASSERT_TRUE(f.good());
  254. // Now check that it is the correct size as reported.
  255. EXPECT_EQ(size, static_cast<int64_t>(f.tellg()));
  256. // Finally, check that it's really a JSON.
  257. ElementPtr from_file = Element::fromJSONFile(exp_txt);
  258. ASSERT_TRUE(from_file);
  259. } else if (exp_status == CONTROL_RESULT_ERROR) {
  260. // Let's check if the reason for failure was given.
  261. ConstElementPtr text = rsp->get("text");
  262. ASSERT_TRUE(text);
  263. ASSERT_EQ(Element::string, text->getType());
  264. EXPECT_EQ(exp_txt, text->stringValue());
  265. } else {
  266. ADD_FAILURE() << "Invalid expected status: " << exp_status;
  267. }
  268. }
  269. /// @brief Command handler which generates long response
  270. static ConstElementPtr longResponseHandler(const std::string&,
  271. const ConstElementPtr&) {
  272. ElementPtr arguments = Element::createList();
  273. std::string arg = "responseresponseresponseresponseresponseresponse"
  274. "response";
  275. for (unsigned i = 0; i < 8000; ++i) {
  276. arguments->add(Element::create(arg));
  277. }
  278. return (createAnswer(0, arguments));
  279. }
  280. };
  281. TEST_F(CtrlChannelDhcpv4SrvTest, commands) {
  282. ASSERT_NO_THROW(
  283. server_.reset(new NakedControlledDhcpv4Srv());
  284. );
  285. // Use empty parameters list
  286. ElementPtr params(new isc::data::MapElement());
  287. int rcode = -1;
  288. // Case 1: send bogus command
  289. ConstElementPtr result = ControlledDhcpv4Srv::processCommand("blah", params);
  290. ConstElementPtr comment = parseAnswer(rcode, result);
  291. EXPECT_EQ(1, rcode); // expect failure (no such command as blah)
  292. // Case 2: send shutdown command without any parameters
  293. result = ControlledDhcpv4Srv::processCommand("shutdown", params);
  294. comment = parseAnswer(rcode, result);
  295. EXPECT_EQ(0, rcode); // expect success
  296. const pid_t pid(getpid());
  297. ConstElementPtr x(new isc::data::IntElement(pid));
  298. params->set("pid", x);
  299. // Case 3: send shutdown command with 1 parameter: pid
  300. result = ControlledDhcpv4Srv::processCommand("shutdown", params);
  301. comment = parseAnswer(rcode, result);
  302. EXPECT_EQ(0, rcode); // expect success
  303. }
  304. // Check that the "libreload" command will reload libraries
  305. TEST_F(CtrlChannelDhcpv4SrvTest, libreload) {
  306. createUnixChannelServer();
  307. // Ensure no marker files to start with.
  308. ASSERT_FALSE(checkMarkerFileExists(LOAD_MARKER_FILE));
  309. ASSERT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));
  310. // Load two libraries
  311. HookLibsCollection libraries;
  312. libraries.push_back(make_pair(CALLOUT_LIBRARY_1, ConstElementPtr()));
  313. libraries.push_back(make_pair(CALLOUT_LIBRARY_2, ConstElementPtr()));
  314. HooksManager::loadLibraries(libraries);
  315. // Check they are loaded.
  316. std::vector<std::string> loaded_libraries =
  317. HooksManager::getLibraryNames();
  318. ASSERT_TRUE(extractNames(libraries) == loaded_libraries);
  319. // ... which also included checking that the marker file created by the
  320. // load functions exists and holds the correct value (of "12" - the
  321. // first library appends "1" to the file, the second appends "2"). Also
  322. // check that the unload marker file does not yet exist.
  323. EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "12"));
  324. EXPECT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));
  325. // Now execute the "libreload" command. This should cause the libraries
  326. // to unload and to reload.
  327. std::string response;
  328. sendUnixCommand("{ \"command\": \"libreload\" }", response);
  329. EXPECT_EQ("{ \"result\": 0, "
  330. "\"text\": \"Hooks libraries successfully reloaded.\" }"
  331. , response);
  332. // Check that the libraries have unloaded and reloaded. The libraries are
  333. // unloaded in the reverse order to which they are loaded. When they load,
  334. // they should append information to the loading marker file.
  335. EXPECT_TRUE(checkMarkerFile(UNLOAD_MARKER_FILE, "21"));
  336. EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "1212"));
  337. }
  338. // This test checks which commands are registered by the DHCPv4 server.
  339. TEST_F(CtrlChannelDhcpv4SrvTest, commandsRegistration) {
  340. ConstElementPtr list_cmds = createCommand("list-commands");
  341. ConstElementPtr answer;
  342. // By default the list should be empty (except the standard list-commands
  343. // supported by the CommandMgr itself)
  344. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  345. ASSERT_TRUE(answer);
  346. ASSERT_TRUE(answer->get("arguments"));
  347. EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
  348. // Created server should register several additional commands.
  349. ASSERT_NO_THROW(
  350. server_.reset(new NakedControlledDhcpv4Srv());
  351. );
  352. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  353. ASSERT_TRUE(answer);
  354. ASSERT_TRUE(answer->get("arguments"));
  355. std::string command_list = answer->get("arguments")->str();
  356. EXPECT_TRUE(command_list.find("\"list-commands\"") != string::npos);
  357. EXPECT_TRUE(command_list.find("\"build-report\"") != string::npos);
  358. EXPECT_TRUE(command_list.find("\"config-get\"") != string::npos);
  359. EXPECT_TRUE(command_list.find("\"config-set\"") != string::npos);
  360. EXPECT_TRUE(command_list.find("\"config-write\"") != string::npos);
  361. EXPECT_TRUE(command_list.find("\"leases-reclaim\"") != string::npos);
  362. EXPECT_TRUE(command_list.find("\"libreload\"") != string::npos);
  363. EXPECT_TRUE(command_list.find("\"shutdown\"") != string::npos);
  364. EXPECT_TRUE(command_list.find("\"statistic-get\"") != string::npos);
  365. EXPECT_TRUE(command_list.find("\"statistic-get-all\"") != string::npos);
  366. EXPECT_TRUE(command_list.find("\"statistic-remove\"") != string::npos);
  367. EXPECT_TRUE(command_list.find("\"statistic-remove-all\"") != string::npos);
  368. EXPECT_TRUE(command_list.find("\"statistic-reset\"") != string::npos);
  369. EXPECT_TRUE(command_list.find("\"statistic-reset-all\"") != string::npos);
  370. EXPECT_TRUE(command_list.find("\"version-get\"") != string::npos);
  371. // Ok, and now delete the server. It should deregister its commands.
  372. server_.reset();
  373. // The list should be (almost) empty again.
  374. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  375. ASSERT_TRUE(answer);
  376. ASSERT_TRUE(answer->get("arguments"));
  377. EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
  378. }
  379. // Tests that the server properly responds to invalid commands sent
  380. // via ControlChannel
  381. TEST_F(CtrlChannelDhcpv4SrvTest, controlChannelNegative) {
  382. createUnixChannelServer();
  383. std::string response;
  384. sendUnixCommand("{ \"command\": \"bogus\" }", response);
  385. EXPECT_EQ("{ \"result\": 2,"
  386. " \"text\": \"'bogus' command not supported.\" }", response);
  387. sendUnixCommand("utter nonsense", response);
  388. EXPECT_EQ("{ \"result\": 1, "
  389. "\"text\": \"invalid first character u : "
  390. "current state: [ 12 RECEIVE_START_ST ] next event: [ 1 START_EVT ]\" }",
  391. response);
  392. }
  393. // Tests that the server properly responds to shtudown command sent
  394. // via ControlChannel
  395. TEST_F(CtrlChannelDhcpv4SrvTest, controlChannelShutdown) {
  396. createUnixChannelServer();
  397. std::string response;
  398. sendUnixCommand("{ \"command\": \"shutdown\" }", response);
  399. EXPECT_EQ("{ \"result\": 0, \"text\": \"Shutting down.\" }",response);
  400. }
  401. // This test verifies that the DHCP server immediately reclaims expired
  402. // leases on leases-reclaim command
  403. TEST_F(CtrlChannelDhcpv4SrvTest, controlLeasesReclaim) {
  404. createUnixChannelServer();
  405. // Create expired leases. Leases are expired by 40 seconds ago
  406. // (valid lifetime = 60, cltt = now - 100).
  407. HWAddrPtr hwaddr0(new HWAddr(HWAddr::fromText("00:01:02:03:04:05")));
  408. Lease4Ptr lease0(new Lease4(IOAddress("10.0.0.1"), hwaddr0,
  409. ClientIdPtr(), 60, 10, 20,
  410. time(NULL) - 100, SubnetID(1)));
  411. HWAddrPtr hwaddr1(new HWAddr(HWAddr::fromText("01:02:03:04:05:06")));
  412. Lease4Ptr lease1(new Lease4(IOAddress("10.0.0.2"), hwaddr1,
  413. ClientIdPtr(), 60, 10, 20,
  414. time(NULL) - 100, SubnetID(1)));
  415. // Add leases to the database.
  416. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  417. ASSERT_NO_THROW(lease_mgr.addLease(lease0));
  418. ASSERT_NO_THROW(lease_mgr.addLease(lease1));
  419. // Make sure they have been added.
  420. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.1")));
  421. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.2")));
  422. // No arguments
  423. std::string response;
  424. sendUnixCommand("{ \"command\": \"leases-reclaim\" }", response);
  425. EXPECT_EQ("{ \"result\": 1, \"text\": "
  426. "\"Missing mandatory 'remove' parameter.\" }", response);
  427. // Bad argument name
  428. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  429. "\"arguments\": { \"reclaim\": true } }", response);
  430. EXPECT_EQ("{ \"result\": 1, \"text\": "
  431. "\"Missing mandatory 'remove' parameter.\" }", response);
  432. // Bad remove argument type
  433. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  434. "\"arguments\": { \"remove\": \"bogus\" } }", response);
  435. EXPECT_EQ("{ \"result\": 1, \"text\": "
  436. "\"'remove' parameter expected to be a boolean.\" }", response);
  437. // Send the command
  438. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  439. "\"arguments\": { \"remove\": false } }", response);
  440. EXPECT_EQ("{ \"result\": 0, \"text\": "
  441. "\"Reclamation of expired leases is complete.\" }", response);
  442. // Leases should be reclaimed, but not removed
  443. ASSERT_NO_THROW(lease0 = lease_mgr.getLease4(IOAddress("10.0.0.1")));
  444. ASSERT_NO_THROW(lease1 = lease_mgr.getLease4(IOAddress("10.0.0.2")));
  445. ASSERT_TRUE(lease0);
  446. ASSERT_TRUE(lease1);
  447. EXPECT_TRUE(lease0->stateExpiredReclaimed());
  448. EXPECT_TRUE(lease1->stateExpiredReclaimed());
  449. }
  450. // This test verifies that the DHCP server handles version-get commands
  451. TEST_F(CtrlChannelDhcpv4SrvTest, getversion) {
  452. createUnixChannelServer();
  453. std::string response;
  454. // Send the version-get command
  455. sendUnixCommand("{ \"command\": \"version-get\" }", response);
  456. EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
  457. EXPECT_TRUE(response.find("log4cplus") != string::npos);
  458. EXPECT_FALSE(response.find("GTEST_VERSION") != string::npos);
  459. // Send the build-report command
  460. sendUnixCommand("{ \"command\": \"build-report\" }", response);
  461. EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
  462. EXPECT_TRUE(response.find("GTEST_VERSION") != string::npos);
  463. }
  464. // This test verifies that the DHCP server immediately removed expired
  465. // This test verifies that the DHCP server immediately removed expired
  466. // leases on leases-reclaim command with remove = true
  467. TEST_F(CtrlChannelDhcpv4SrvTest, controlLeasesReclaimRemove) {
  468. createUnixChannelServer();
  469. // Create expired leases. Leases are expired by 40 seconds ago
  470. // (valid lifetime = 60, cltt = now - 100).
  471. HWAddrPtr hwaddr0(new HWAddr(HWAddr::fromText("00:01:02:03:04:05")));
  472. Lease4Ptr lease0(new Lease4(IOAddress("10.0.0.1"), hwaddr0,
  473. ClientIdPtr(), 60, 10, 20,
  474. time(NULL) - 100, SubnetID(1)));
  475. HWAddrPtr hwaddr1(new HWAddr(HWAddr::fromText("01:02:03:04:05:06")));
  476. Lease4Ptr lease1(new Lease4(IOAddress("10.0.0.2"), hwaddr1,
  477. ClientIdPtr(), 60, 10, 20,
  478. time(NULL) - 100, SubnetID(1)));
  479. // Add leases to the database.
  480. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  481. ASSERT_NO_THROW(lease_mgr.addLease(lease0));
  482. ASSERT_NO_THROW(lease_mgr.addLease(lease1));
  483. // Make sure they have been added.
  484. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.1")));
  485. ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.2")));
  486. // Send the command
  487. std::string response;
  488. sendUnixCommand("{ \"command\": \"leases-reclaim\", "
  489. "\"arguments\": { \"remove\": true } }", response);
  490. EXPECT_EQ("{ \"result\": 0, \"text\": "
  491. "\"Reclamation of expired leases is complete.\" }", response);
  492. // Leases should have been removed.
  493. ASSERT_NO_THROW(lease0 = lease_mgr.getLease4(IOAddress("10.0.0.1")));
  494. ASSERT_NO_THROW(lease1 = lease_mgr.getLease4(IOAddress("10.0.0.2")));
  495. EXPECT_FALSE(lease0);
  496. EXPECT_FALSE(lease1);
  497. }
  498. // Tests that the server properly responds to statistics commands. Note this
  499. // is really only intended to verify that the appropriate Statistics handler
  500. // is called based on the command. It is not intended to be an exhaustive
  501. // test of Dhcpv4 statistics.
  502. TEST_F(CtrlChannelDhcpv4SrvTest, controlChannelStats) {
  503. createUnixChannelServer();
  504. std::string response;
  505. // Check statistic-get
  506. sendUnixCommand("{ \"command\" : \"statistic-get\", "
  507. " \"arguments\": {"
  508. " \"name\":\"bogus\" }}", response);
  509. EXPECT_EQ("{ \"arguments\": { }, \"result\": 0 }", response);
  510. // Check statistic-get-all
  511. sendUnixCommand("{ \"command\" : \"statistic-get-all\", "
  512. " \"arguments\": {}}", response);
  513. EXPECT_EQ("{ \"arguments\": { }, \"result\": 0 }", response);
  514. // Check statistic-reset
  515. sendUnixCommand("{ \"command\" : \"statistic-reset\", "
  516. " \"arguments\": {"
  517. " \"name\":\"bogus\" }}", response);
  518. EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
  519. response);
  520. // Check statistic-reset-all
  521. sendUnixCommand("{ \"command\" : \"statistic-reset-all\", "
  522. " \"arguments\": {}}", response);
  523. EXPECT_EQ("{ \"result\": 0, \"text\": "
  524. "\"All statistics reset to neutral values.\" }", response);
  525. // Check statistic-remove
  526. sendUnixCommand("{ \"command\" : \"statistic-remove\", "
  527. " \"arguments\": {"
  528. " \"name\":\"bogus\" }}", response);
  529. EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
  530. response);
  531. // Check statistic-remove-all
  532. sendUnixCommand("{ \"command\" : \"statistic-remove-all\", "
  533. " \"arguments\": {}}", response);
  534. EXPECT_EQ("{ \"result\": 0, \"text\": \"All statistics removed.\" }",
  535. response);
  536. }
  537. // Check that the "config-set" command will replace current configuration
  538. TEST_F(CtrlChannelDhcpv4SrvTest, configSet) {
  539. createUnixChannelServer();
  540. // Define strings to permutate the config arguments
  541. // (Note the line feeds makes errors easy to find)
  542. string set_config_txt = "{ \"command\": \"config-set\" \n";
  543. string args_txt = " \"arguments\": { \n";
  544. string dhcp4_cfg_txt =
  545. " \"Dhcp4\": { \n"
  546. " \"interfaces-config\": { \n"
  547. " \"interfaces\": [\"*\"] \n"
  548. " }, \n"
  549. " \"valid-lifetime\": 4000, \n"
  550. " \"renew-timer\": 1000, \n"
  551. " \"rebind-timer\": 2000, \n"
  552. " \"lease-database\": { \n"
  553. " \"type\": \"memfile\", \n"
  554. " \"persist\":false, \n"
  555. " \"lfc-interval\": 0 \n"
  556. " }, \n"
  557. " \"expired-leases-processing\": { \n"
  558. " \"reclaim-timer-wait-time\": 0, \n"
  559. " \"hold-reclaimed-time\": 0, \n"
  560. " \"flush-reclaimed-timer-wait-time\": 0 \n"
  561. " },"
  562. " \"subnet4\": [ \n";
  563. string subnet1 =
  564. " {\"subnet\": \"192.2.0.0/24\", \n"
  565. " \"pools\": [{ \"pool\": \"192.2.0.1-192.2.0.50\" }]}\n";
  566. string subnet2 =
  567. " {\"subnet\": \"192.2.1.0/24\", \n"
  568. " \"pools\": [{ \"pool\": \"192.2.1.1-192.2.1.50\" }]}\n";
  569. string bad_subnet =
  570. " {\"BOGUS\": \"192.2.2.0/24\", \n"
  571. " \"pools\": [{ \"pool\": \"192.2.2.1-192.2.2.50\" }]}\n";
  572. string subnet_footer =
  573. " ] \n";
  574. string control_socket_header =
  575. " ,\"control-socket\": { \n"
  576. " \"socket-type\": \"unix\", \n"
  577. " \"socket-name\": \"";
  578. string control_socket_footer =
  579. "\" \n} \n";
  580. string logger_txt =
  581. " \"Logging\": { \n"
  582. " \"loggers\": [ { \n"
  583. " \"name\": \"kea\", \n"
  584. " \"severity\": \"FATAL\", \n"
  585. " \"output_options\": [{ \n"
  586. " \"output\": \"/dev/null\" \n"
  587. " }] \n"
  588. " }] \n"
  589. " } \n";
  590. std::ostringstream os;
  591. // Create a valid config with all the parts should parse
  592. os << set_config_txt << ","
  593. << args_txt
  594. << dhcp4_cfg_txt
  595. << subnet1
  596. << subnet_footer
  597. << control_socket_header
  598. << socket_path_
  599. << control_socket_footer
  600. << "}\n" // close dhcp4
  601. << ","
  602. << logger_txt
  603. << "}}";
  604. // Send the config-set command
  605. std::string response;
  606. sendUnixCommand(os.str(), response);
  607. // Verify the configuration was successful.
  608. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
  609. response);
  610. // Check that the config was indeed applied.
  611. const Subnet4Collection* subnets =
  612. CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  613. EXPECT_EQ(1, subnets->size());
  614. // Create a config with malformed subnet that should fail to parse.
  615. os.str("");
  616. os << set_config_txt << ","
  617. << args_txt
  618. << dhcp4_cfg_txt
  619. << bad_subnet
  620. << subnet_footer
  621. << control_socket_header
  622. << socket_path_
  623. << control_socket_footer
  624. << "}\n" // close dhcp4
  625. "}}";
  626. // Send the config-set command
  627. sendUnixCommand(os.str(), response);
  628. // Should fail with a syntax error
  629. EXPECT_EQ("{ \"result\": 1, "
  630. "\"text\": \"subnet configuration failed: mandatory 'subnet' "
  631. "parameter is missing for a subnet being configured (<wire>:19:17)\" }",
  632. response);
  633. // Check that the config was not lost
  634. subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  635. EXPECT_EQ(1, subnets->size());
  636. // Create a valid config with two subnets and no command channel.
  637. // It should succeed, client should still receive the response
  638. os.str("");
  639. os << set_config_txt << ","
  640. << args_txt
  641. << dhcp4_cfg_txt
  642. << subnet1
  643. << ",\n"
  644. << subnet2
  645. << subnet_footer
  646. << "}\n" // close dhcp4
  647. << "}}";
  648. // Verify the control channel socket exists.
  649. ASSERT_TRUE(fileExists(socket_path_));
  650. // Send the config-set command.
  651. sendUnixCommand(os.str(), response);
  652. // Verify the control channel socket no longer exists.
  653. EXPECT_FALSE(fileExists(socket_path_));
  654. // With no command channel, should still receive the response.
  655. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
  656. response);
  657. // Check that the config was not lost
  658. subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  659. EXPECT_EQ(2, subnets->size());
  660. // Clean up after the test.
  661. CfgMgr::instance().clear();
  662. }
  663. // Tests that the server properly responds to shtudown command sent
  664. // via ControlChannel
  665. TEST_F(CtrlChannelDhcpv4SrvTest, listCommands) {
  666. createUnixChannelServer();
  667. std::string response;
  668. sendUnixCommand("{ \"command\": \"list-commands\" }", response);
  669. ConstElementPtr rsp;
  670. EXPECT_NO_THROW(rsp = Element::fromJSON(response));
  671. // We expect the server to report at least the following commands:
  672. checkListCommands(rsp, "build-report");
  673. checkListCommands(rsp, "config-get");
  674. checkListCommands(rsp, "config-reload");
  675. checkListCommands(rsp, "config-set");
  676. checkListCommands(rsp, "config-write");
  677. checkListCommands(rsp, "list-commands");
  678. checkListCommands(rsp, "leases-reclaim");
  679. checkListCommands(rsp, "libreload");
  680. checkListCommands(rsp, "shutdown");
  681. checkListCommands(rsp, "statistic-get");
  682. checkListCommands(rsp, "statistic-get-all");
  683. checkListCommands(rsp, "statistic-remove");
  684. checkListCommands(rsp, "statistic-remove-all");
  685. checkListCommands(rsp, "statistic-reset");
  686. checkListCommands(rsp, "statistic-reset-all");
  687. checkListCommands(rsp, "version-get");
  688. }
  689. // Tests if the server returns its configuration using config-get.
  690. // Note there are separate tests that verify if toElement() called by the
  691. // config-get handler are actually converting the configuration correctly.
  692. TEST_F(CtrlChannelDhcpv4SrvTest, configGet) {
  693. createUnixChannelServer();
  694. std::string response;
  695. sendUnixCommand("{ \"command\": \"config-get\" }", response);
  696. ConstElementPtr rsp;
  697. // The response should be a valid JSON.
  698. EXPECT_NO_THROW(rsp = Element::fromJSON(response));
  699. ASSERT_TRUE(rsp);
  700. int status;
  701. ConstElementPtr cfg = parseAnswer(status, rsp);
  702. EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
  703. // Ok, now roughly check if the response seems legit.
  704. ASSERT_TRUE(cfg);
  705. ASSERT_EQ(Element::map, cfg->getType());
  706. EXPECT_TRUE(cfg->get("Dhcp4"));
  707. }
  708. // Verify that the "config-test" command will do what we expect.
  709. TEST_F(CtrlChannelDhcpv4SrvTest, configTest) {
  710. createUnixChannelServer();
  711. // Define strings to permutate the config arguments
  712. // (Note the line feeds makes errors easy to find)
  713. string set_config_txt = "{ \"command\": \"config-set\" \n";
  714. string config_test_txt = "{ \"command\": \"config-test\" \n";
  715. string args_txt = " \"arguments\": { \n";
  716. string dhcp4_cfg_txt =
  717. " \"Dhcp4\": { \n"
  718. " \"interfaces-config\": { \n"
  719. " \"interfaces\": [\"*\"] \n"
  720. " }, \n"
  721. " \"valid-lifetime\": 4000, \n"
  722. " \"renew-timer\": 1000, \n"
  723. " \"rebind-timer\": 2000, \n"
  724. " \"lease-database\": { \n"
  725. " \"type\": \"memfile\", \n"
  726. " \"persist\":false, \n"
  727. " \"lfc-interval\": 0 \n"
  728. " }, \n"
  729. " \"expired-leases-processing\": { \n"
  730. " \"reclaim-timer-wait-time\": 0, \n"
  731. " \"hold-reclaimed-time\": 0, \n"
  732. " \"flush-reclaimed-timer-wait-time\": 0 \n"
  733. " },"
  734. " \"subnet4\": [ \n";
  735. string subnet1 =
  736. " {\"subnet\": \"192.2.0.0/24\", \n"
  737. " \"pools\": [{ \"pool\": \"192.2.0.1-192.2.0.50\" }]}\n";
  738. string subnet2 =
  739. " {\"subnet\": \"192.2.1.0/24\", \n"
  740. " \"pools\": [{ \"pool\": \"192.2.1.1-192.2.1.50\" }]}\n";
  741. string bad_subnet =
  742. " {\"BOGUS\": \"192.2.2.0/24\", \n"
  743. " \"pools\": [{ \"pool\": \"192.2.2.1-192.2.2.50\" }]}\n";
  744. string subnet_footer =
  745. " ] \n";
  746. string control_socket_header =
  747. " ,\"control-socket\": { \n"
  748. " \"socket-type\": \"unix\", \n"
  749. " \"socket-name\": \"";
  750. string control_socket_footer =
  751. "\" \n} \n";
  752. string logger_txt =
  753. " \"Logging\": { \n"
  754. " \"loggers\": [ { \n"
  755. " \"name\": \"kea\", \n"
  756. " \"severity\": \"FATAL\", \n"
  757. " \"output_options\": [{ \n"
  758. " \"output\": \"/dev/null\" \n"
  759. " }] \n"
  760. " }] \n"
  761. " } \n";
  762. std::ostringstream os;
  763. // Create a valid config with all the parts should parse
  764. os << set_config_txt << ","
  765. << args_txt
  766. << dhcp4_cfg_txt
  767. << subnet1
  768. << subnet_footer
  769. << control_socket_header
  770. << socket_path_
  771. << control_socket_footer
  772. << "}\n" // close dhcp4
  773. << ","
  774. << logger_txt
  775. << "}}";
  776. // Send the config-set command
  777. std::string response;
  778. sendUnixCommand(os.str(), response);
  779. // Verify the configuration was successful.
  780. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
  781. response);
  782. // Check that the config was indeed applied.
  783. const Subnet4Collection* subnets =
  784. CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  785. EXPECT_EQ(1, subnets->size());
  786. // Create a config with malformed subnet that should fail to parse.
  787. os.str("");
  788. os << config_test_txt << ","
  789. << args_txt
  790. << dhcp4_cfg_txt
  791. << bad_subnet
  792. << subnet_footer
  793. << control_socket_header
  794. << socket_path_
  795. << control_socket_footer
  796. << "}\n" // close dhcp4
  797. "}}";
  798. // Send the config-test command
  799. sendUnixCommand(os.str(), response);
  800. // Should fail with a syntax error
  801. EXPECT_EQ("{ \"result\": 1, "
  802. "\"text\": \"subnet configuration failed: mandatory 'subnet' "
  803. "parameter is missing for a subnet being configured (<wire>:19:17)\" }",
  804. response);
  805. // Check that the config was not lost
  806. subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  807. EXPECT_EQ(1, subnets->size());
  808. // Create a valid config with two subnets and no command channel.
  809. os.str("");
  810. os << config_test_txt << ","
  811. << args_txt
  812. << dhcp4_cfg_txt
  813. << subnet1
  814. << ",\n"
  815. << subnet2
  816. << subnet_footer
  817. << "}\n" // close dhcp4
  818. << "}}";
  819. // Verify the control channel socket exists.
  820. ASSERT_TRUE(fileExists(socket_path_));
  821. // Send the config-test command
  822. sendUnixCommand(os.str(), response);
  823. // Verify the control channel socket still exists.
  824. EXPECT_TRUE(fileExists(socket_path_));
  825. // Verify the configuration was successful.
  826. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration seems sane. "
  827. "Control-socket, hook-libraries, and D2 configuration were "
  828. "sanity checked, but not applied.\" }",
  829. response);
  830. // Check that the config was not applied
  831. subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  832. EXPECT_EQ(1, subnets->size());
  833. // Clean up after the test.
  834. CfgMgr::instance().clear();
  835. }
  836. // Tests if config-write can be called without any parameters.
  837. TEST_F(CtrlChannelDhcpv4SrvTest, writeConfigNoFilename) {
  838. createUnixChannelServer();
  839. std::string response;
  840. // This is normally set by the command line -c parameter.
  841. server_->setConfigFile("test1.json");
  842. // If the filename is not explicitly specified, the name used
  843. // in -c command line switch is used.
  844. sendUnixCommand("{ \"command\": \"config-write\" }", response);
  845. checkConfigWrite(response, CONTROL_RESULT_SUCCESS, "test1.json");
  846. ::remove("test1.json");
  847. }
  848. // Tests if config-write can be called with a valid filename as parameter.
  849. TEST_F(CtrlChannelDhcpv4SrvTest, writeConfigFilename) {
  850. createUnixChannelServer();
  851. std::string response;
  852. sendUnixCommand("{ \"command\": \"config-write\", "
  853. "\"arguments\": { \"filename\": \"test2.json\" } }", response);
  854. checkConfigWrite(response, CONTROL_RESULT_SUCCESS, "test2.json");
  855. ::remove("test2.json");
  856. }
  857. // Tests if config-reload attempts to reload a file and reports that the
  858. // file is missing.
  859. TEST_F(CtrlChannelDhcpv4SrvTest, configReloadMissingFile) {
  860. createUnixChannelServer();
  861. std::string response;
  862. // This is normally set to whatever value is passed to -c when the server is
  863. // started, but we're not starting it that way, so need to set it by hand.
  864. server_->setConfigFile("test6.json");
  865. // Tell the server to reload its configuration. It should attempt to load
  866. // test6.json (and fail, because the file is not there).
  867. sendUnixCommand("{ \"command\": \"config-reload\" }", response);
  868. // Verify the reload was rejected.
  869. EXPECT_EQ("{ \"result\": 1, \"text\": \"Config reload failed:"
  870. "configuration error using file 'test6.json': Unable to open file "
  871. "test6.json\" }",
  872. response);
  873. }
  874. // Tests if config-reload attempts to reload a file and reports that the
  875. // file is not a valid JSON.
  876. TEST_F(CtrlChannelDhcpv4SrvTest, configReloadBrokenFile) {
  877. createUnixChannelServer();
  878. std::string response;
  879. // This is normally set to whatever value is passed to -c when the server is
  880. // started, but we're not starting it that way, so need to set it by hand.
  881. server_->setConfigFile("test7.json");
  882. // Although Kea is smart, its AI routines are not smart enough to handle
  883. // this one... at least not yet.
  884. ofstream f("test7.json", ios::trunc);
  885. f << "gimme some addrs, bro!";
  886. f.close();
  887. // Now tell Kea to reload its config.
  888. sendUnixCommand("{ \"command\": \"config-reload\" }", response);
  889. // Verify the reload will fail.
  890. EXPECT_EQ("{ \"result\": 1, \"text\": \"Config reload failed:"
  891. "configuration error using file 'test7.json': "
  892. "test7.json:1.1: Invalid character: g\" }",
  893. response);
  894. ::remove("test7.json");
  895. }
  896. // Tests if config-reload attempts to reload a file and reports that the
  897. // file is loaded correctly.
  898. TEST_F(CtrlChannelDhcpv4SrvTest, configReloadValid) {
  899. createUnixChannelServer();
  900. std::string response;
  901. // This is normally set to whatever value is passed to -c when the server is
  902. // started, but we're not starting it that way, so need to set it by hand.
  903. server_->setConfigFile("test8.json");
  904. // Ok, enough fooling around. Let's create a valid config.
  905. const std::string cfg_txt =
  906. "{ \"Dhcp4\": {"
  907. " \"interfaces-config\": {"
  908. " \"interfaces\": [ \"*\" ]"
  909. " },"
  910. " \"subnet4\": ["
  911. " { \"subnet\": \"192.0.2.0/24\" },"
  912. " { \"subnet\": \"192.0.3.0/24\" }"
  913. " ],"
  914. " \"valid-lifetime\": 4000,"
  915. " \"lease-database\": {"
  916. " \"type\": \"memfile\", \"persist\": false }"
  917. "} }";
  918. ofstream f("test8.json", ios::trunc);
  919. f << cfg_txt;
  920. f.close();
  921. // This command should reload test8.json config.
  922. sendUnixCommand("{ \"command\": \"config-reload\" }", response);
  923. // Verify the configuration was successful.
  924. EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
  925. response);
  926. // Check that the config was indeed applied.
  927. const Subnet4Collection* subnets =
  928. CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
  929. EXPECT_EQ(2, subnets->size());
  930. ::remove("test8.json");
  931. }
  932. /// Verify that concurrent connections over the control channel can be
  933. /// established.
  934. /// @todo Future Kea 1.3 tickets will modify the behavior of the CommandMgr
  935. /// such that the server will be able to send response in multiple chunks.
  936. /// This test will need to be extended. For now, the receive and write
  937. /// operations are atomic and there is no conflict between concurrent
  938. /// connections.
  939. TEST_F(CtrlChannelDhcpv4SrvTest, concurrentConnections) {
  940. createUnixChannelServer();
  941. boost::scoped_ptr<UnixControlClient> client1(new UnixControlClient());
  942. ASSERT_TRUE(client1);
  943. boost::scoped_ptr<UnixControlClient> client2(new UnixControlClient());
  944. ASSERT_TRUE(client2);
  945. // Client 1 connects.
  946. ASSERT_TRUE(client1->connectToServer(socket_path_));
  947. ASSERT_NO_THROW(getIOService()->poll());
  948. // Client 2 connects.
  949. ASSERT_TRUE(client2->connectToServer(socket_path_));
  950. ASSERT_NO_THROW(getIOService()->poll());
  951. // Send the command while another client is connected.
  952. ASSERT_TRUE(client2->sendCommand("{ \"command\": \"list-commands\" }"));
  953. ASSERT_NO_THROW(getIOService()->poll());
  954. std::string response;
  955. // The server should respond ok.
  956. ASSERT_TRUE(client2->getResponse(response));
  957. EXPECT_TRUE(response.find("\"result\": 0") != std::string::npos);
  958. // Disconnect the servers.
  959. client1->disconnectFromServer();
  960. client2->disconnectFromServer();
  961. ASSERT_NO_THROW(getIOService()->poll());
  962. }
  963. // This test verifies that the server can receive and process a large command.
  964. TEST_F(CtrlChannelDhcpv4SrvTest, longCommand) {
  965. createUnixChannelServer();
  966. std::string response;
  967. std::thread th([this, &response]() {
  968. // IO service will be stopped automatically when this object goes
  969. // out of scope and is destroyed. This is useful because we use
  970. // asserts which may break the thread in various exit points.
  971. IOServiceWork work(getIOService());
  972. // Create client which we will use to send command to the server.
  973. boost::scoped_ptr<UnixControlClient> client(new UnixControlClient());
  974. ASSERT_TRUE(client);
  975. // Connect to the server. This will trigger acceptor handler on the
  976. // server side and create a new connection.
  977. ASSERT_TRUE(client->connectToServer(socket_path_));
  978. // This counter will hold the number of bytes transferred to the server
  979. // so far.
  980. size_t bytes_transferred = 0;
  981. // This is the desired size of the command sent to the server (1MB). The
  982. // actual size sent will be slightly greater than that.
  983. const size_t command_size = 1024 * 1000;
  984. bool first_payload = true;
  985. // If we still haven't sent the entire command, continue sending.
  986. while (bytes_transferred < command_size) {
  987. // We're sending command 'foo' with arguments being a list of
  988. // strings. If this is the first transmission, send command name
  989. // and open the arguments list.
  990. if (bytes_transferred == 0) {
  991. std::string preamble = "{ \"command\": \"foo\", \"arguments\": [ ";
  992. ASSERT_TRUE(client->sendCommand(preamble));
  993. // Store the number of bytes sent.
  994. bytes_transferred += preamble.size();
  995. } else {
  996. // We have already transmitted command name and arguments. Now
  997. // we send the list of 'blabla' strings.
  998. std::ostringstream payload;
  999. // If this is not the first parameter in on the list it must be
  1000. // prefixed with a comma.
  1001. if (!first_payload) {
  1002. payload << ", ";
  1003. }
  1004. first_payload = false;
  1005. payload << "\"blablablablablablablablablablablablablablablabla\"";
  1006. // If we have hit the limit of the command size, close braces to
  1007. // get appropriate JSON.
  1008. if (bytes_transferred + payload.tellp() > command_size) {
  1009. payload << "] }";
  1010. }
  1011. // Send the payload.
  1012. ASSERT_TRUE(client->sendCommand(payload.str()));
  1013. // Update the number of bytes sent.
  1014. bytes_transferred += payload.tellp();
  1015. }
  1016. }
  1017. // Set timeout to 5 seconds to allow the time for the server to send
  1018. // a response.
  1019. const unsigned int timeout = 5;
  1020. ASSERT_TRUE(client->getResponse(response, timeout));
  1021. // We're done. Close the connection to the server.
  1022. client->disconnectFromServer();
  1023. });
  1024. // Run the server until the command has been processed and response
  1025. // received.
  1026. getIOService()->run();
  1027. // Wait for the thread to complete.
  1028. th.join();
  1029. EXPECT_EQ("{ \"result\": 2, \"text\": \"'foo' command not supported.\" }",
  1030. response);
  1031. }
  1032. // This test verifies that the server can send long response to the client.
  1033. TEST_F(CtrlChannelDhcpv4SrvTest, longResponse) {
  1034. // We need to generate large response. The simplest way is to create
  1035. // a command and a handler which will generate some static response
  1036. // of a desired size.
  1037. ASSERT_NO_THROW(
  1038. CommandMgr::instance().registerCommand("foo",
  1039. boost::bind(&CtrlChannelDhcpv4SrvTest::longResponseHandler, _1, _2));
  1040. );
  1041. createUnixChannelServer();
  1042. // The UnixControlClient doesn't have any means to check that the entire
  1043. // response has been received. What we want to do is to generate a
  1044. // reference response using our command handler and then compare
  1045. // what we have received over the unix domain socket with this reference
  1046. // response to figure out when to stop receiving.
  1047. std::string reference_response = longResponseHandler("foo", ConstElementPtr())->str();
  1048. // In this stream we're going to collect out partial responses.
  1049. std::ostringstream response;
  1050. // The client is synchronous so it is useful to run it in a thread.
  1051. std::thread th([this, &response, reference_response]() {
  1052. // IO service will be stopped automatically when this object goes
  1053. // out of scope and is destroyed. This is useful because we use
  1054. // asserts which may break the thread in various exit points.
  1055. IOServiceWork work(getIOService());
  1056. // Remember the response size so as we know when we should stop
  1057. // receiving.
  1058. const size_t long_response_size = reference_response.size();
  1059. // Create the client and connect it to the server.
  1060. boost::scoped_ptr<UnixControlClient> client(new UnixControlClient());
  1061. ASSERT_TRUE(client);
  1062. ASSERT_TRUE(client->connectToServer(socket_path_));
  1063. // Send the stub command.
  1064. std::string command = "{ \"command\": \"foo\", \"arguments\": { } }";
  1065. ASSERT_TRUE(client->sendCommand(command));
  1066. // Keep receiving response data until we have received the full answer.
  1067. while (response.tellp() < long_response_size) {
  1068. std::string partial;
  1069. const unsigned int timeout = 5;
  1070. ASSERT_TRUE(client->getResponse(partial, 5));
  1071. response << partial;
  1072. }
  1073. // We have received the entire response, so close the connection and
  1074. // stop the IO service.
  1075. client->disconnectFromServer();
  1076. });
  1077. // Run the server until the entire response has been received.
  1078. getIOService()->run();
  1079. // Wait for the thread to complete.
  1080. th.join();
  1081. // Make sure we have received correct response.
  1082. EXPECT_EQ(reference_response, response.str());
  1083. }
  1084. // This test verifies that the server signals timeout if the transmission
  1085. // takes too long.
  1086. TEST_F(CtrlChannelDhcpv4SrvTest, connectionTimeout) {
  1087. createUnixChannelServer();
  1088. // Server's response will be assigned to this variable.
  1089. std::string response;
  1090. // It is useful to create a thread and run the server and the client
  1091. // at the same time and independently.
  1092. std::thread th([this, &response]() {
  1093. // IO service will be stopped automatically when this object goes
  1094. // out of scope and is destroyed. This is useful because we use
  1095. // asserts which may break the thread in various exit points.
  1096. IOServiceWork work(getIOService());
  1097. // Create the client and connect it to the server.
  1098. boost::scoped_ptr<UnixControlClient> client(new UnixControlClient());
  1099. ASSERT_TRUE(client);
  1100. ASSERT_TRUE(client->connectToServer(socket_path_));
  1101. // Send partial command. The server will be waiting for the remaining
  1102. // part to be sent and will eventually signal a timeout.
  1103. std::string command = "{ \"command\": \"foo\" ";
  1104. ASSERT_TRUE(client->sendCommand(command));
  1105. // Let's wait up to 10s for the server's response. The response
  1106. // should arrive sooner assuming that the timeout mechanism for
  1107. // the server is working properly.
  1108. const unsigned int timeout = 10;
  1109. ASSERT_TRUE(client->getResponse(response, 10));
  1110. // Explicitly close the client's connection.
  1111. client->disconnectFromServer();
  1112. });
  1113. // Run the server until stopped.
  1114. getIOService()->run();
  1115. // Wait for the thread to return.
  1116. th.join();
  1117. // Check that the server has signalled a timeout.
  1118. EXPECT_EQ("{ \"result\": 1, \"text\": \"Connection over control channel"
  1119. " timed out\" }", response);
  1120. }
  1121. } // End of anonymous namespace