mysql_lease_mgr_unittest.cc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // Copyright (C) 2012-2014 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <asiolink/io_address.h>
  16. #include <dhcpsrv/lease_mgr_factory.h>
  17. #include <dhcpsrv/mysql_connection.h>
  18. #include <dhcpsrv/mysql_lease_mgr.h>
  19. #include <dhcpsrv/tests/test_utils.h>
  20. #include <dhcpsrv/tests/generic_lease_mgr_unittest.h>
  21. #include <exceptions/exceptions.h>
  22. #include <gtest/gtest.h>
  23. #include <algorithm>
  24. #include <iostream>
  25. #include <sstream>
  26. #include <string>
  27. #include <utility>
  28. using namespace isc;
  29. using namespace isc::asiolink;
  30. using namespace isc::dhcp;
  31. using namespace isc::dhcp::test;
  32. using namespace std;
  33. namespace {
  34. // This holds statements to create and destroy the schema.
  35. #include "schema_mysql_copy.h"
  36. // Connection strings.
  37. // Database: keatest
  38. // Host: localhost
  39. // Username: keatest
  40. // Password: keatest
  41. const char* VALID_TYPE = "type=mysql";
  42. const char* INVALID_TYPE = "type=unknown";
  43. const char* VALID_NAME = "name=keatest";
  44. const char* INVALID_NAME = "name=invalidname";
  45. const char* VALID_HOST = "host=localhost";
  46. const char* INVALID_HOST = "host=invalidhost";
  47. const char* VALID_USER = "user=keatest";
  48. const char* INVALID_USER = "user=invaliduser";
  49. const char* VALID_PASSWORD = "password=keatest";
  50. const char* INVALID_PASSWORD = "password=invalid";
  51. // Given a combination of strings above, produce a connection string.
  52. string connectionString(const char* type, const char* name, const char* host,
  53. const char* user, const char* password) {
  54. const string space = " ";
  55. string result = "";
  56. if (type != NULL) {
  57. result += string(type);
  58. }
  59. if (name != NULL) {
  60. if (! result.empty()) {
  61. result += space;
  62. }
  63. result += string(name);
  64. }
  65. if (host != NULL) {
  66. if (! result.empty()) {
  67. result += space;
  68. }
  69. result += string(host);
  70. }
  71. if (user != NULL) {
  72. if (! result.empty()) {
  73. result += space;
  74. }
  75. result += string(user);
  76. }
  77. if (password != NULL) {
  78. if (! result.empty()) {
  79. result += space;
  80. }
  81. result += string(password);
  82. }
  83. return (result);
  84. }
  85. // Return valid connection string
  86. string
  87. validConnectionString() {
  88. return (connectionString(VALID_TYPE, VALID_NAME, VALID_HOST,
  89. VALID_USER, VALID_PASSWORD));
  90. }
  91. // @brief Clear everything from the database
  92. //
  93. // There is no error checking in this code: if something fails, one of the
  94. // tests will (should) fall over.
  95. void destroySchema() {
  96. MySqlHolder mysql;
  97. // Open database
  98. (void) mysql_real_connect(mysql, "localhost", "keatest",
  99. "keatest", "keatest", 0, NULL, 0);
  100. // Get rid of everything in it.
  101. for (int i = 0; destroy_statement[i] != NULL; ++i) {
  102. (void) mysql_query(mysql, destroy_statement[i]);
  103. }
  104. }
  105. // @brief Create the Schema
  106. //
  107. // Creates all the tables in what is assumed to be an empty database.
  108. //
  109. // There is no error checking in this code: if it fails, one of the tests
  110. // will fall over.
  111. void createSchema() {
  112. MySqlHolder mysql;
  113. // Open database
  114. (void) mysql_real_connect(mysql, "localhost", "keatest",
  115. "keatest", "keatest", 0, NULL, 0);
  116. // Execute creation statements.
  117. for (int i = 0; create_statement[i] != NULL; ++i) {
  118. ASSERT_EQ(0, mysql_query(mysql, create_statement[i]))
  119. << "Failed on statement " << i << ": " << create_statement[i];
  120. }
  121. }
  122. /// @brief Test fixture class for testing MySQL Lease Manager
  123. ///
  124. /// Opens the database prior to each test and closes it afterwards.
  125. /// All pending transactions are deleted prior to closure.
  126. class MySqlLeaseMgrTest : public GenericLeaseMgrTest {
  127. public:
  128. /// @brief Constructor
  129. ///
  130. /// Deletes everything from the database and opens it.
  131. MySqlLeaseMgrTest() {
  132. // Ensure schema is the correct one.
  133. destroySchema();
  134. createSchema();
  135. // Connect to the database
  136. try {
  137. LeaseMgrFactory::create(validConnectionString());
  138. } catch (...) {
  139. std::cerr << "*** ERROR: unable to open database. The test\n"
  140. "*** environment is broken and must be fixed before\n"
  141. "*** the MySQL tests will run correctly.\n"
  142. "*** The reason for the problem is described in the\n"
  143. "*** accompanying exception output.\n";
  144. throw;
  145. }
  146. lmptr_ = &(LeaseMgrFactory::instance());
  147. }
  148. /// @brief Destructor
  149. ///
  150. /// Rolls back all pending transactions. The deletion of lmptr_ will close
  151. /// the database. Then reopen it and delete everything created by the test.
  152. virtual ~MySqlLeaseMgrTest() {
  153. lmptr_->rollback();
  154. LeaseMgrFactory::destroy();
  155. destroySchema();
  156. }
  157. /// @brief Reopen the database
  158. ///
  159. /// Closes the database and re-open it. Anything committed should be
  160. /// visible.
  161. ///
  162. /// Parameter is ignored for MySQL backend as the v4 and v6 leases share
  163. /// the same database.
  164. void reopen(Universe) {
  165. LeaseMgrFactory::destroy();
  166. LeaseMgrFactory::create(validConnectionString());
  167. lmptr_ = &(LeaseMgrFactory::instance());
  168. }
  169. };
  170. /// @brief Check that database can be opened
  171. ///
  172. /// This test checks if the MySqlLeaseMgr can be instantiated. This happens
  173. /// only if the database can be opened. Note that this is not part of the
  174. /// MySqlLeaseMgr test fixure set. This test checks that the database can be
  175. /// opened: the fixtures assume that and check basic operations.
  176. TEST(MySqlOpenTest, OpenDatabase) {
  177. // Schema needs to be created for the test to work.
  178. destroySchema();
  179. createSchema();
  180. // Check that lease manager open the database opens correctly and tidy up.
  181. // If it fails, print the error message.
  182. try {
  183. LeaseMgrFactory::create(validConnectionString());
  184. EXPECT_NO_THROW((void) LeaseMgrFactory::instance());
  185. LeaseMgrFactory::destroy();
  186. } catch (const isc::Exception& ex) {
  187. FAIL() << "*** ERROR: unable to open database, reason:\n"
  188. << " " << ex.what() << "\n"
  189. << "*** The test environment is broken and must be fixed\n"
  190. << "*** before the MySQL tests will run correctly.\n";
  191. }
  192. // Check that attempting to get an instance of the lease manager when
  193. // none is set throws an exception.
  194. EXPECT_THROW(LeaseMgrFactory::instance(), NoLeaseManager);
  195. // Check that wrong specification of backend throws an exception.
  196. // (This is really a check on LeaseMgrFactory, but is convenient to
  197. // perform here.)
  198. EXPECT_THROW(LeaseMgrFactory::create(connectionString(
  199. NULL, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
  200. InvalidParameter);
  201. EXPECT_THROW(LeaseMgrFactory::create(connectionString(
  202. INVALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
  203. InvalidType);
  204. // Check that invalid login data causes an exception.
  205. EXPECT_THROW(LeaseMgrFactory::create(connectionString(
  206. VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
  207. DbOpenError);
  208. EXPECT_THROW(LeaseMgrFactory::create(connectionString(
  209. VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
  210. DbOpenError);
  211. EXPECT_THROW(LeaseMgrFactory::create(connectionString(
  212. VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
  213. DbOpenError);
  214. EXPECT_THROW(LeaseMgrFactory::create(connectionString(
  215. VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)),
  216. DbOpenError);
  217. // Check for missing parameters
  218. EXPECT_THROW(LeaseMgrFactory::create(connectionString(
  219. VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
  220. NoDatabaseName);
  221. // Tidy up after the test
  222. destroySchema();
  223. }
  224. /// @brief Check the getType() method
  225. ///
  226. /// getType() returns a string giving the type of the backend, which should
  227. /// always be "mysql".
  228. TEST_F(MySqlLeaseMgrTest, getType) {
  229. EXPECT_EQ(std::string("mysql"), lmptr_->getType());
  230. }
  231. /// @brief Check conversion functions
  232. ///
  233. /// The server works using cltt and valid_filetime. In the database, the
  234. /// information is stored as expire_time and valid-lifetime, which are
  235. /// related by
  236. ///
  237. /// expire_time = cltt + valid_lifetime
  238. ///
  239. /// This test checks that the conversion is correct. It does not check that the
  240. /// data is entered into the database correctly, only that the MYSQL_TIME
  241. /// structure used for the entry is correctly set up.
  242. TEST_F(MySqlLeaseMgrTest, checkTimeConversion) {
  243. const time_t cltt = time(NULL);
  244. const uint32_t valid_lft = 86400; // 1 day
  245. struct tm tm_expire;
  246. MYSQL_TIME mysql_expire;
  247. // Work out what the broken-down time will be for one day
  248. // after the current time.
  249. time_t expire_time = cltt + valid_lft;
  250. (void) localtime_r(&expire_time, &tm_expire);
  251. // Convert to the database time
  252. MySqlConnection::convertToDatabaseTime(cltt, valid_lft, mysql_expire);
  253. // Are the times the same?
  254. EXPECT_EQ(tm_expire.tm_year + 1900, mysql_expire.year);
  255. EXPECT_EQ(tm_expire.tm_mon + 1, mysql_expire.month);
  256. EXPECT_EQ(tm_expire.tm_mday, mysql_expire.day);
  257. EXPECT_EQ(tm_expire.tm_hour, mysql_expire.hour);
  258. EXPECT_EQ(tm_expire.tm_min, mysql_expire.minute);
  259. EXPECT_EQ(tm_expire.tm_sec, mysql_expire.second);
  260. EXPECT_EQ(0, mysql_expire.second_part);
  261. EXPECT_EQ(0, mysql_expire.neg);
  262. // Convert back
  263. time_t converted_cltt = 0;
  264. MySqlConnection::convertFromDatabaseTime(mysql_expire, valid_lft, converted_cltt);
  265. EXPECT_EQ(cltt, converted_cltt);
  266. }
  267. /// @brief Check getName() returns correct database name
  268. TEST_F(MySqlLeaseMgrTest, getName) {
  269. EXPECT_EQ(std::string("keatest"), lmptr_->getName());
  270. }
  271. /// @brief Check that getVersion() returns the expected version
  272. TEST_F(MySqlLeaseMgrTest, checkVersion) {
  273. // Check version
  274. pair<uint32_t, uint32_t> version;
  275. ASSERT_NO_THROW(version = lmptr_->getVersion());
  276. EXPECT_EQ(CURRENT_VERSION_VERSION, version.first);
  277. EXPECT_EQ(CURRENT_VERSION_MINOR, version.second);
  278. }
  279. ////////////////////////////////////////////////////////////////////////////////
  280. /// LEASE4 /////////////////////////////////////////////////////////////////////
  281. ////////////////////////////////////////////////////////////////////////////////
  282. /// @brief Basic Lease4 Checks
  283. ///
  284. /// Checks that the addLease, getLease4 (by address) and deleteLease (with an
  285. /// IPv4 address) works.
  286. TEST_F(MySqlLeaseMgrTest, basicLease4) {
  287. testBasicLease4();
  288. }
  289. /// @brief Check that Lease4 code safely handles invalid dates.
  290. TEST_F(MySqlLeaseMgrTest, maxDate4) {
  291. testMaxDate4();
  292. }
  293. /// @brief Lease4 update tests
  294. ///
  295. /// Checks that we are able to update a lease in the database.
  296. TEST_F(MySqlLeaseMgrTest, updateLease4) {
  297. testUpdateLease4();
  298. }
  299. /// @brief Check GetLease4 methods - access by Hardware Address
  300. TEST_F(MySqlLeaseMgrTest, getLease4HWAddr1) {
  301. testGetLease4HWAddr1();
  302. }
  303. /// @brief Check GetLease4 methods - access by Hardware Address
  304. TEST_F(MySqlLeaseMgrTest, getLease4HWAddr2) {
  305. testGetLease4HWAddr2();
  306. }
  307. // @brief Get lease4 by hardware address (2)
  308. //
  309. // Check that the system can cope with getting a hardware address of
  310. // any size.
  311. TEST_F(MySqlLeaseMgrTest, getLease4HWAddrSize) {
  312. testGetLease4HWAddrSize();
  313. }
  314. /// @brief Check GetLease4 methods - access by Hardware Address & Subnet ID
  315. ///
  316. /// Adds leases to the database and checks that they can be accessed via
  317. /// a combination of hardware address and subnet ID
  318. TEST_F(MySqlLeaseMgrTest, getLease4HwaddrSubnetId) {
  319. testGetLease4HWAddrSubnetId();
  320. }
  321. // @brief Get lease4 by hardware address and subnet ID (2)
  322. //
  323. // Check that the system can cope with getting a hardware address of
  324. // any size.
  325. TEST_F(MySqlLeaseMgrTest, getLease4HWAddrSubnetIdSize) {
  326. testGetLease4HWAddrSubnetIdSize();
  327. }
  328. // This test was derived from memfile.
  329. TEST_F(MySqlLeaseMgrTest, getLease4ClientId) {
  330. testGetLease4ClientId();
  331. }
  332. /// @brief Check GetLease4 methods - access by Client ID
  333. ///
  334. /// Adds leases to the database and checks that they can be accessed via
  335. /// the Client ID.
  336. TEST_F(MySqlLeaseMgrTest, getLease4ClientId2) {
  337. testGetLease4ClientId2();
  338. }
  339. // @brief Get Lease4 by client ID (2)
  340. //
  341. // Check that the system can cope with a client ID of any size.
  342. TEST_F(MySqlLeaseMgrTest, getLease4ClientIdSize) {
  343. testGetLease4ClientIdSize();
  344. }
  345. /// @brief Check GetLease4 methods - access by Client ID & Subnet ID
  346. ///
  347. /// Adds leases to the database and checks that they can be accessed via
  348. /// a combination of client and subnet IDs.
  349. TEST_F(MySqlLeaseMgrTest, getLease4ClientIdSubnetId) {
  350. testGetLease4ClientIdSubnetId();
  351. }
  352. /// @brief Basic Lease4 Checks
  353. ///
  354. /// Checks that the addLease, getLease4(by address), getLease4(hwaddr,subnet_id),
  355. /// updateLease4() and deleteLease (IPv4 address) can handle NULL client-id.
  356. /// (client-id is optional and may not be present)
  357. TEST_F(MySqlLeaseMgrTest, lease4NullClientId) {
  358. testLease4NullClientId();
  359. }
  360. /// @brief Verify that too long hostname for Lease4 is not accepted.
  361. ///
  362. /// Checks that the it is not possible to create a lease when the hostname
  363. /// length exceeds 255 characters.
  364. TEST_F(MySqlLeaseMgrTest, lease4InvalidHostname) {
  365. testLease4InvalidHostname();
  366. }
  367. ////////////////////////////////////////////////////////////////////////////////
  368. /// LEASE6 /////////////////////////////////////////////////////////////////////
  369. ////////////////////////////////////////////////////////////////////////////////
  370. // Test checks whether simple add, get and delete operations are possible
  371. // on Lease6
  372. TEST_F(MySqlLeaseMgrTest, testAddGetDelete6) {
  373. testAddGetDelete6(false);
  374. }
  375. /// @brief Basic Lease6 Checks
  376. ///
  377. /// Checks that the addLease, getLease6 (by address) and deleteLease (with an
  378. /// IPv6 address) works.
  379. TEST_F(MySqlLeaseMgrTest, basicLease6) {
  380. testBasicLease6();
  381. }
  382. /// @brief Check that Lease6 code safely handles invalid dates.
  383. TEST_F(MySqlLeaseMgrTest, maxDate6) {
  384. testMaxDate6();
  385. }
  386. /// @brief Verify that too long hostname for Lease6 is not accepted.
  387. ///
  388. /// Checks that the it is not possible to create a lease when the hostname
  389. /// length exceeds 255 characters.
  390. TEST_F(MySqlLeaseMgrTest, lease6InvalidHostname) {
  391. testLease6InvalidHostname();
  392. }
  393. /// @brief Check GetLease6 methods - access by DUID/IAID
  394. ///
  395. /// Adds leases to the database and checks that they can be accessed via
  396. /// a combination of DUID and IAID.
  397. TEST_F(MySqlLeaseMgrTest, getLeases6DuidIaid) {
  398. testGetLeases6DuidIaid();
  399. }
  400. // Check that the system can cope with a DUID of allowed size.
  401. TEST_F(MySqlLeaseMgrTest, getLeases6DuidSize) {
  402. testGetLeases6DuidSize();
  403. }
  404. /// @brief Check that getLease6 methods discriminate by lease type.
  405. ///
  406. /// Adds six leases, two per lease type all with the same duid and iad but
  407. /// with alternating subnet_ids.
  408. /// It then verifies that all of getLeases6() method variants correctly
  409. /// discriminate between the leases based on lease type alone.
  410. TEST_F(MySqlLeaseMgrTest, lease6LeaseTypeCheck) {
  411. testLease6LeaseTypeCheck();
  412. }
  413. /// @brief Check GetLease6 methods - access by DUID/IAID/SubnetID
  414. ///
  415. /// Adds leases to the database and checks that they can be accessed via
  416. /// a combination of DIUID and IAID.
  417. TEST_F(MySqlLeaseMgrTest, getLease6DuidIaidSubnetId) {
  418. testGetLease6DuidIaidSubnetId();
  419. }
  420. // Test checks that getLease6() works with different DUID sizes
  421. TEST_F(MySqlLeaseMgrTest, getLease6DuidIaidSubnetIdSize) {
  422. testGetLease6DuidIaidSubnetIdSize();
  423. }
  424. /// @brief Lease6 update tests
  425. ///
  426. /// Checks that we are able to update a lease in the database.
  427. TEST_F(MySqlLeaseMgrTest, updateLease6) {
  428. testUpdateLease6();
  429. }
  430. /// @brief DHCPv4 Lease recreation tests
  431. ///
  432. /// Checks that the lease can be created, deleted and recreated with
  433. /// different parameters. It also checks that the re-created lease is
  434. /// correctly stored in the lease database.
  435. TEST_F(MySqlLeaseMgrTest, testRecreateLease4) {
  436. testRecreateLease4();
  437. }
  438. /// @brief DHCPv6 Lease recreation tests
  439. ///
  440. /// Checks that the lease can be created, deleted and recreated with
  441. /// different parameters. It also checks that the re-created lease is
  442. /// correctly stored in the lease database.
  443. TEST_F(MySqlLeaseMgrTest, testRecreateLease6) {
  444. testRecreateLease6();
  445. }
  446. /// @brief Checks that null DUID is not allowed.
  447. TEST_F(MySqlLeaseMgrTest, nullDuid) {
  448. testNullDuid();
  449. }
  450. /// @brief Tests whether memfile can store and retrieve hardware addresses
  451. TEST_F(MySqlLeaseMgrTest, testLease6Mac) {
  452. testLease6MAC();
  453. }
  454. /// @brief Tests whether memfile can store and retrieve hardware addresses
  455. TEST_F(MySqlLeaseMgrTest, testLease6HWTypeAndSource) {
  456. testLease6HWTypeAndSource();
  457. }
  458. /// @brief Check that the expired DHCPv4 leases can be retrieved.
  459. ///
  460. /// This test adds a number of leases to the lease database and marks
  461. /// some of them as expired. Then it queries for expired leases and checks
  462. /// whether only expired leases are returned, and that they are returned in
  463. /// the order from most to least expired. It also checks that the lease
  464. /// which is marked as 'reclaimed' is not returned.
  465. TEST_F(MySqlLeaseMgrTest, getExpiredLeases4) {
  466. testGetExpiredLeases4();
  467. }
  468. /// @brief Check that the expired DHCPv6 leases can be retrieved.
  469. ///
  470. /// This test adds a number of leases to the lease database and marks
  471. /// some of them as expired. Then it queries for expired leases and checks
  472. /// whether only expired leases are returned, and that they are returned in
  473. /// the order from most to least expired. It also checks that the lease
  474. /// which is marked as 'reclaimed' is not returned.
  475. TEST_F(MySqlLeaseMgrTest, getExpiredLeases6) {
  476. testGetExpiredLeases6();
  477. }
  478. /// @brief Check that expired reclaimed DHCPv6 leases are removed.
  479. TEST_F(MySqlLeaseMgrTest, deleteExpiredReclaimedLeases6) {
  480. testDeleteExpiredReclaimedLeases6();
  481. }
  482. /// @brief Check that expired reclaimed DHCPv4 leases are removed.
  483. TEST_F(MySqlLeaseMgrTest, deleteExpiredReclaimedLeases4) {
  484. testDeleteExpiredReclaimedLeases4();
  485. }
  486. }; // Of anonymous namespace