alloc_engine_expiration_unittest.cc 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007
  1. // Copyright (C) 2015 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 <dhcp/duid.h>
  16. #include <dhcp/option_data_types.h>
  17. #include <dhcp_ddns/ncr_msg.h>
  18. #include <dhcpsrv/tests/alloc_engine_utils.h>
  19. #include <dhcpsrv/tests/test_utils.h>
  20. #include <hooks/hooks_manager.h>
  21. #include <stats/stats_mgr.h>
  22. #include <gtest/gtest.h>
  23. #include <boost/bind.hpp>
  24. #include <boost/function.hpp>
  25. #include <boost/static_assert.hpp>
  26. #include <iomanip>
  27. #include <sstream>
  28. #include <time.h>
  29. #include <unistd.h>
  30. #include <vector>
  31. using namespace std;
  32. using namespace isc;
  33. using namespace isc::asiolink;
  34. using namespace isc::dhcp;
  35. using namespace isc::dhcp::test;
  36. using namespace isc::dhcp_ddns;
  37. using namespace isc::hooks;
  38. using namespace isc::stats;
  39. namespace {
  40. /// @brief Number of leases to be initialized for each test.
  41. ///
  42. /// This value is expected by some of the tests to be multiple
  43. /// of 10.
  44. const unsigned int TEST_LEASES_NUM = 100;
  45. /// @brief Structure wrapping a lower limit within the collection
  46. /// of leases.
  47. ///
  48. /// We're using this structure rather than a size_t value directly
  49. /// to make API of the test fixture class more readable, i.e. the
  50. /// struct name indicates the purpose of the value being held.
  51. struct LowerBound {
  52. /// @brief Constructor.
  53. ///
  54. /// @param lower_bound Interger value wrapped by the structure.
  55. explicit LowerBound(const size_t lower_bound)
  56. : lower_bound_(lower_bound) { };
  57. /// @brief Operator returning the size_t value wrapped.
  58. operator size_t() const {
  59. return (lower_bound_);
  60. }
  61. /// @brief Value wrapped in the structure.
  62. size_t lower_bound_;
  63. };
  64. /// @brief Structure wrapping an upper limit within the collection
  65. /// of leases.
  66. ///
  67. /// We're using this structure rather than a size_t value directly
  68. /// to make API of the test fixture class more readable, i.e. the
  69. /// struct name indicates the purpose of the value being held.
  70. struct UpperBound {
  71. /// @brief Constructor.
  72. ///
  73. /// @param lower_bound Interger value wrapped by the structure.
  74. explicit UpperBound(const size_t upper_bound)
  75. : upper_bound_(upper_bound) { };
  76. /// @brief Operator returning the size_t value wrapped.
  77. operator size_t() const {
  78. return (upper_bound_);
  79. }
  80. /// @brief Value wrapped in the structure.
  81. size_t upper_bound_;
  82. };
  83. /// @brief List holding addresses for executed callouts.
  84. std::list<IOAddress> callouts_;
  85. /// @brief Callout argument name for expired lease.
  86. std::string callout_argument_name("lease4");
  87. /// @brief Base test fixture class for the lease reclamation routines in the
  88. /// @c AllocEngine.
  89. ///
  90. /// This class implements infrastructure for testing leases reclamation
  91. /// routines. The lease reclamation routine has the following
  92. /// characteristic:
  93. /// - it processes multiple leases,
  94. /// - leases are processed in certain order,
  95. /// - number of processed leases may be limited by the parameters,
  96. /// - maxium duration of the lease reclamation routine may be limited,
  97. /// - reclaimed leases may be marked as reclaimed or deleted,
  98. /// - DNS records for some of the leases must be removed when the lease
  99. /// is reclaimed and DNS updates are enabled,
  100. /// - hooks must be invoked (if installed) for each reclaimed lease
  101. /// - statistics must be updated to increase the number of reclaimed
  102. /// leases and decrease the number of allocated leases
  103. ///
  104. /// The typical test requires many leases to be initialized and stored
  105. /// in the lease database for the test. The test fixture class creates
  106. /// these leases upon construction. It is possible to modify these
  107. /// leases to test various properties of the lease reclamation routine
  108. /// as listed above. For example: some of the leases may be marked
  109. /// as expired or hostname may be cleared for some of the leases to
  110. /// check that DNS updates are not generated for them.
  111. ///
  112. /// The tests are built around the
  113. /// @c ExpirationAllocEngineTest::testLeases methods. These methods
  114. /// verify that the certain operations have been performed by the
  115. /// lease reclamation routine on selected leases. The leases for which
  116. /// certain conditions should be met are selected using the "index
  117. /// algorithms". Various index algorithms are implemented in the
  118. /// test fixture class as static functions and the algorithm is
  119. /// selected by passing function pointer to the @c testLeases method.
  120. ///
  121. /// Examples of index algorithms are:
  122. /// - evenLeaseIndex(index) - picks even index numbers,
  123. /// - oddLeaseIndex(index) - picks odd index numbers,
  124. /// - allLeasesIndexes(index) - picks all index number.
  125. ///
  126. /// For example, the test may use the @c evenLeaseIndex algorithm
  127. /// to mark leases with even indexes as expired and then test whether
  128. /// leases with even indexes have been successfully reclaimed.
  129. ///
  130. /// The "lease algorithm" verifies if the given lease fulfils the
  131. /// specific conditions after reclamation. These are the examples of
  132. /// the lease algorithms:
  133. /// - leaseExists - lease still exists in the database,
  134. /// - leaseDoesntExist - lease removed from the database,
  135. /// - leaseReclaimed - lease exists but has reclaimed status,
  136. /// - leaseNotReclaimed - lease exists and is not in the reclaimed status,
  137. /// - leaseDeclined - lease exists and is in declined state,
  138. /// - dnsUpdateGeneratedForLease - DNS updates generated for lease,
  139. /// - dnsUpdateNotGeneratedForLease - DNS updates not generated for lease
  140. ///
  141. /// The combination of index algorithm and lease algorithm allows for
  142. /// verifying that the whole sets of leases in the lease database fulfil
  143. /// certain conditions. For example, it is possible to verify that
  144. /// after lease reclamation leases with even indexes have state set to
  145. /// "expired-reclaimed".
  146. ///
  147. /// See @c ExpirationAllocEngineTest::testLeases for further details.
  148. ///
  149. /// @todo These tests should be extended to cover the following cases:
  150. /// - declined leases - declined leases expire and should be removed
  151. /// from the lease database by the lease reclamation routine. See
  152. /// ticket #3976.
  153. template<typename LeasePtrType>
  154. class ExpirationAllocEngineTest : public ::testing::Test {
  155. public:
  156. /// @brief Type definition for the lease algorithm.
  157. typedef boost::function<bool (const LeasePtrType)> LeaseAlgorithmFun;
  158. /// @brief type definition for the lease index algorithm.
  159. typedef boost::function<bool (const size_t)> IndexAlgorithmFun;
  160. /// @brief Constructor.
  161. ///
  162. /// Clears configuration, creates new lease manager and allocation engine
  163. /// instances.
  164. ExpirationAllocEngineTest(const std::string& lease_mgr_params) {
  165. // Clear configuration.
  166. CfgMgr::instance().clear();
  167. D2ClientConfigPtr cfg(new D2ClientConfig());
  168. CfgMgr::instance().setD2ClientConfig(cfg);
  169. // Remove all statistics.
  170. StatsMgr::instance().resetAll();
  171. // Create lease manager.
  172. LeaseMgrFactory::create(lease_mgr_params);
  173. // Create allocation engine instance.
  174. engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  175. 100, false));
  176. }
  177. /// @brief Destructor
  178. ///
  179. /// Stops D2 client (if running), clears configuration and removes
  180. /// an instance of the lease manager.
  181. virtual ~ExpirationAllocEngineTest() {
  182. // Stop D2 client if running and remove all queued name change
  183. // requests.
  184. D2ClientMgr& mgr = CfgMgr::instance().getD2ClientMgr();
  185. if (mgr.amSending()) {
  186. mgr.stopSender();
  187. mgr.clearQueue();
  188. }
  189. // Clear configuration.
  190. CfgMgr::instance().clear();
  191. D2ClientConfigPtr cfg(new D2ClientConfig());
  192. CfgMgr::instance().setD2ClientConfig(cfg);
  193. // Remove all statistics.
  194. StatsMgr::instance().resetAll();
  195. // Kill lease manager.
  196. LeaseMgrFactory::destroy();
  197. // Remove callouts executed.
  198. callouts_.clear();
  199. }
  200. /// @brief Starts D2 client.
  201. void enableDDNS() const {
  202. // Start DDNS and assign no-op error handler.
  203. D2ClientMgr& mgr = CfgMgr::instance().getD2ClientMgr();
  204. D2ClientConfigPtr cfg(new D2ClientConfig());
  205. cfg->enableUpdates(true);
  206. mgr.setD2ClientConfig(cfg);
  207. mgr.startSender(boost::bind(&ExpirationAllocEngineTest::d2ErrorHandler, _1, _2));
  208. }
  209. /// @brief No-op error handler for the D2 client.
  210. static void d2ErrorHandler(const dhcp_ddns::NameChangeSender::Result,
  211. dhcp_ddns::NameChangeRequestPtr&) {
  212. }
  213. /// @brief Marks a lease as expired.
  214. ///
  215. /// @param lease_index Lease index. Must be between 0 and
  216. /// @c TEST_LEASES_NUM.
  217. /// @param secs Offset of the expiration time since now. For example
  218. /// a value of 2 would set the lease expiration time to 2 seconds ago.
  219. void expire(const uint16_t lease_index, const time_t secs) {
  220. ASSERT_GT(leases_.size(), lease_index);
  221. // We set the expiration time indirectly by modifying the cltt value.
  222. leases_[lease_index]->cltt_ = time(NULL) - secs -
  223. leases_[lease_index]->valid_lft_;
  224. ASSERT_NO_THROW(updateLease(lease_index));
  225. }
  226. /// @brief Marks lease as expired-reclaimed.
  227. ///
  228. /// @param lease_index Lease index. Must be between 0 and
  229. /// @c TEST_LEASES_NUM.
  230. /// @param secs Offset of the expiration time since now. For example
  231. /// a value of 2 would set the lease expiration time to 2 seconds ago.
  232. void reclaim(const uint16_t lease_index, const time_t secs) {
  233. ASSERT_GT(leases_.size(), lease_index);
  234. leases_[lease_index]->cltt_ = time(NULL) - secs -
  235. leases_[lease_index]->valid_lft_;
  236. leases_[lease_index]->state_ = Lease::STATE_EXPIRED_RECLAIMED;
  237. ASSERT_NO_THROW(updateLease(lease_index));
  238. }
  239. /// @brief Declines specified lease
  240. ///
  241. /// Sets specified lease to declined state and sets its probation-period.
  242. /// @param lease_index Index of the lease.
  243. /// @param probation_time value of probation period to be set (in seconds)
  244. void decline(const uint16_t lease_index, const time_t probation_time) {
  245. ASSERT_GT(leases_.size(), lease_index);
  246. leases_[lease_index]->decline(probation_time);
  247. ASSERT_NO_THROW(updateLease(lease_index));
  248. }
  249. /// @brief Updates lease in the lease database.
  250. ///
  251. /// @param lease_index Index of the lease.
  252. virtual void updateLease(const unsigned int lease_index) = 0;
  253. /// @brief Retrieves lease from the database.
  254. ///
  255. /// @param lease_index Index of the lease.
  256. virtual LeasePtrType getLease(const unsigned int lease_index) const = 0;
  257. /// @brief Sets subnet id for a lease.
  258. ///
  259. /// It also updates statistics of assigned leases in the stats manager.
  260. ///
  261. /// @param lease_index Lease index.
  262. /// @param id New subnet id.
  263. virtual void setSubnetId(const uint16_t lease_index, const SubnetID& id) = 0;
  264. /// @brief Wrapper method running lease reclamation routine.
  265. ///
  266. /// @param max_leases Maximum number of leases to be reclaimed.
  267. /// @param timeout Maximum amount of time that the reclaimation routine
  268. /// may be processing expired leases, expressed in seconds.
  269. /// @param remove_lease A boolean value indicating if the lease should
  270. /// be removed when it is reclaimed (if true) or it should be left in the
  271. /// database in the "expired-reclaimed" state (if false).
  272. virtual void reclaimExpiredLeases(const size_t max_leases,
  273. const uint16_t timeout,
  274. const bool remove_lease) = 0;
  275. /// @brief Wrapper method for removing expired-reclaimed leases.
  276. ///
  277. /// @param secs The minimum amount of time, expressed in seconds,
  278. /// for the lease to be left in the "expired-reclaimed" state
  279. /// before it can be removed.
  280. virtual void deleteExpiredReclaimedLeases(const uint32_t secs) = 0;
  281. /// @brief Test selected leases using the specified algorithms.
  282. ///
  283. /// This function picks leases from the range of 0 thru
  284. /// @c TEST_LEASES_NUM and selects the ones to be verified using the
  285. /// specified index algorithm. Selected leases are tested using
  286. /// the specified lease algorithm.
  287. ///
  288. /// @param lease_algorithm Pointer to the lease algorithm function.
  289. /// @param index_algorithm Pointer to the index algorithm function.
  290. bool testLeases(const LeaseAlgorithmFun& lease_algorithm,
  291. const IndexAlgorithmFun& index_algorithm) const {
  292. // No limits are specified, so test all leases in the range of
  293. // 0 .. TEST_LEASES_NUM.
  294. return (testLeases(lease_algorithm, index_algorithm, LowerBound(0),
  295. UpperBound(TEST_LEASES_NUM)));
  296. }
  297. /// @brief Test selected leases using the specified algorithms.
  298. ///
  299. /// This function picks leases from the range of @c lower_bound
  300. /// thru @c upper_bound and selects the ones to be verified using the
  301. /// specified index algorithm. Selected leases are tested using the
  302. /// specified lease algorithm.
  303. ///
  304. /// @param lease_algorithm Pointer to the lease algorithm function.
  305. /// @param index_algorithm Pointer to the index algorithm function.
  306. /// @param lower_bound First index in the range.
  307. /// @param upper_bound Last + 1 index in the range.
  308. bool testLeases(const LeaseAlgorithmFun& lease_algorithm,
  309. const IndexAlgorithmFun& index_algorithm,
  310. const LowerBound& lower_bound,
  311. const UpperBound& upper_bound) const {
  312. // Select leases between the lower_bound and upper_bound.
  313. for (size_t i = lower_bound; i < upper_bound; ++i) {
  314. // Get the lease from the lease database.
  315. LeasePtrType lease = getLease(i);
  316. // index_algorithm(i) checks if the lease should be checked.
  317. // If so, check if the lease_algorithm indicates that the
  318. // lease fulfils a given condition, e.g. is present in the
  319. // database. If not, return false.
  320. if (index_algorithm(i) && !lease_algorithm(lease)) {
  321. return (false);
  322. }
  323. }
  324. // All leases checked, so return true.
  325. return (true);
  326. }
  327. /// @brief Index algorithm selecting even indexes.
  328. ///
  329. /// @param index Lease index.
  330. /// @return true if index is an even number.
  331. static bool evenLeaseIndex(const size_t index) {
  332. return (index % 2 == 0);
  333. }
  334. /// @brief Index algorithm selecting odd indexes.
  335. ///
  336. /// @param index Lease index.
  337. /// @return true if index is an odd number.
  338. static bool oddLeaseIndex(const size_t index) {
  339. return (!evenLeaseIndex(index));
  340. }
  341. /// @brief Index algorithm selecting all indexes.
  342. ///
  343. /// @param index Lease index.
  344. /// @return true if the index is in the range of [0 .. TEST_LEASES_NUM).
  345. static bool allLeaseIndexes(const size_t index) {
  346. return (index < TEST_LEASES_NUM);
  347. }
  348. /// @brief Lease algorithm checking if lease exists.
  349. ///
  350. /// @param lease Pointer to lease.
  351. /// @return true if lease pointer is non-null.
  352. static bool leaseExists(const LeasePtrType& lease) {
  353. return (static_cast<bool>(lease));
  354. }
  355. /// @brief Lease algorithm checking if lease doesn't exist.
  356. ///
  357. /// @param lease Pointer to lease.
  358. /// @return true if lease pointer is null.
  359. static bool leaseDoesntExist(const LeasePtrType& lease) {
  360. return (static_cast<bool>(!lease));
  361. }
  362. /// @brief Lease algorithm checking if lease state is expired-reclaimed.
  363. ///
  364. /// This algorithm also checks that the FQDN information has been removed
  365. /// from the lease.
  366. ///
  367. /// @param lease Pointer to lease.
  368. /// @return true if lease state is "expired-reclaimed" and the FQDN
  369. /// information has been removed from the lease.
  370. static bool leaseReclaimed(const LeasePtrType& lease) {
  371. return (lease && lease->stateExpiredReclaimed() &&
  372. lease->hostname_.empty() && !lease->fqdn_fwd_ &&
  373. !lease->fqdn_rev_);
  374. }
  375. /// @brief Lease algorithm checking if lease state is Declined.
  376. ///
  377. /// @param lease Pointer to lease.
  378. /// @return true if lease state is "declined".
  379. static bool leaseDeclined(const LeasePtrType& lease) {
  380. return (lease && lease->stateDeclined());
  381. }
  382. /// @brief Lease algorithm checking if lease state is not
  383. /// expired-reclaimed.
  384. ///
  385. /// @param lease Pointer to lease.
  386. /// @return true if lease state is not "expired-reclaimed".
  387. static bool leaseNotReclaimed(const LeasePtrType& lease) {
  388. return (lease && !lease->stateExpiredReclaimed());
  389. }
  390. /// @brief Lease algorithm checking if removal name change request
  391. /// has been generated for lease.
  392. ///
  393. /// @param lease Pointer to lease.
  394. /// @return true if NCR has been generated for the lease.
  395. static bool dnsUpdateGeneratedForLease(const LeasePtrType& lease) {
  396. try {
  397. return (static_cast<bool>(getNCRForLease(lease)));
  398. } catch (...) {
  399. // If error occurred, treat it as no match.
  400. return (false);
  401. }
  402. }
  403. /// @brief Lease algorithm checking if removal name change request
  404. /// hasn't been generated for lease.
  405. ///
  406. /// @param lease Pointer to lease.
  407. /// @return true if NCR has not been generated for the lease.
  408. static bool dnsUpdateNotGeneratedForLease(const LeasePtrType& lease) {
  409. try {
  410. // Iterate over the generated name change requests and try
  411. // to find the match with our lease (using IP address). If
  412. D2ClientMgr& mgr = CfgMgr::instance().getD2ClientMgr();
  413. for (size_t i = 0; i < mgr.getQueueSize(); ++i) {
  414. const NameChangeRequestPtr& ncr = mgr.peekAt(i);
  415. // If match found, we treat it as if the test fails
  416. // because we expected no NCR.
  417. if (ncr->getIpAddress() == lease->addr_.toText()) {
  418. return (false);
  419. }
  420. }
  421. } catch (...) {
  422. return (false);
  423. }
  424. // No match found, so we're good.
  425. return (true);
  426. }
  427. /// @brief Lease algorithm checking if callout has been executed for
  428. /// the expired lease.
  429. ///
  430. /// @param lease Pointer to lease.
  431. /// @return true if callout has been executed for the lease.
  432. static bool leaseCalloutExecuted(const LeasePtrType& lease) {
  433. return (std::find(callouts_.begin(), callouts_.end(), lease->addr_) !=
  434. callouts_.end());
  435. }
  436. /// @brief Lease algorithm checking if callout hasn't been executed for
  437. /// the expired lease.
  438. ///
  439. /// @param lease Pointer to lease.
  440. /// @return true if callout hasn't been executed for the lease.
  441. static bool leaseCalloutNotExecuted(const LeasePtrType& lease) {
  442. return (!leaseCalloutExecuted(lease));
  443. }
  444. /// @brief Implements "lease{4,6}_expire" callout.
  445. ///
  446. /// @param callout_handle Callout handle.
  447. /// @return Zero.
  448. static int leaseExpireCallout(CalloutHandle& callout_handle) {
  449. LeasePtrType lease;
  450. callout_handle.getArgument(callout_argument_name, lease);
  451. bool remove_lease = true;
  452. callout_handle.getArgument("remove_lease", remove_lease);
  453. // Check if the remove_lease is set to false and assume that the callout
  454. // has been successfully executed if it is. This is mainly to test
  455. // that the lease reclamation routine sets this value at all.
  456. if (!remove_lease) {
  457. callouts_.push_back(lease->addr_);
  458. }
  459. return (0);
  460. }
  461. /// @brief Implements "lease{4,6}_expire callout returning skip flag.
  462. ///
  463. /// @param callout_handle Callout handle.
  464. /// @return Zero.
  465. static int leaseExpireWithSkipCallout(CalloutHandle& callout_handle) {
  466. leaseExpireCallout(callout_handle);
  467. callout_handle.setStatus(CalloutHandle::NEXT_STEP_SKIP);
  468. return (0);
  469. }
  470. /// @brief Implements "lease{4,6}_expire callout, which lasts at least
  471. /// 40ms.
  472. ///
  473. /// This callout is useful to test scenarios where the reclamation of the
  474. /// lease needs to take a known amount of time. If the callout is installed
  475. /// it will take at least 40ms for each lease. It is then possible to calculate
  476. /// the approximate time that the reclamation of all leases would take and
  477. /// test that the timeouts for the leases' reclamation work as expected.
  478. ///
  479. /// The value of 40ms is relatively high, but it has been selected to
  480. /// mitigate the problems with usleep on some virtual machines. On those
  481. /// machines the wakeup from usleep may take significant amount of time,
  482. /// i.e. usually around 10ms. Thus, the sleep time should be considerably
  483. /// higher than this delay.
  484. ///
  485. /// @param callout_handle Callout handle.
  486. /// @return Zero.
  487. static int leaseExpireWithDelayCallout(CalloutHandle& callout_handle) {
  488. leaseExpireCallout(callout_handle);
  489. // Delay the return from the callout by 40ms.
  490. usleep(40000);
  491. return (0);
  492. }
  493. /// @brief Returns removal name change request from the D2 client queue.
  494. ///
  495. /// @param lease Pointer to the lease to be matched with NCR.
  496. ///
  497. /// @return null pointer if no match found.
  498. static NameChangeRequestPtr getNCRForLease(const LeasePtrType& lease) {
  499. // Iterate over the generated name change requests and try
  500. // to find the match with our lease (using IP address). If
  501. D2ClientMgr& mgr = CfgMgr::instance().getD2ClientMgr();
  502. for (size_t i = 0; i < mgr.getQueueSize(); ++i) {
  503. const NameChangeRequestPtr& ncr = mgr.peekAt(i);
  504. // If match found, return true.
  505. if ((ncr->getIpAddress() == lease->addr_.toText()) &&
  506. (ncr->getChangeType() == CHG_REMOVE)) {
  507. return (ncr);
  508. }
  509. }
  510. return (NameChangeRequestPtr());
  511. }
  512. /// @brief Returns index of the lease from the address.
  513. ///
  514. /// This method assumes that leases are ordered from the smallest to
  515. /// the highest address, e.g. 10.0.0.0, 10.0.0.1, 10.0.0.2 etc. The
  516. /// last two bytes can be used to extract index.
  517. ///
  518. /// @param address Address.
  519. ///
  520. /// @return index
  521. static uint16_t getLeaseIndexFromAddress(const IOAddress& address) {
  522. std::vector<uint8_t> bytes = address.toBytes();
  523. std::vector<uint8_t>::reverse_iterator bytes_it = bytes.rbegin();
  524. uint16_t index = static_cast<uint16_t>(*bytes_it) |
  525. (static_cast<uint16_t>(*(bytes_it + 1)) << 8);
  526. return (index);
  527. }
  528. /// @brief Generates hostname for lease index.
  529. ///
  530. /// Generates hostname in the form of "hostXXXX.example.org", where
  531. /// XXXX is a lease index.
  532. ///
  533. /// @param index Lease index.
  534. ///
  535. /// @return Generated hostname.
  536. static std::string generateHostnameForLeaseIndex(const uint16_t index) {
  537. std::ostringstream hostname_s;
  538. hostname_s << "host" << std::setw(4) << std::setfill('0')
  539. << index << ".example.org";
  540. return (hostname_s.str());
  541. }
  542. /// @brief Test that leases can be reclaimed without being removed.
  543. void testReclaimExpiredLeasesUpdateState() {
  544. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  545. // Mark leases with even indexes as expired.
  546. if (evenLeaseIndex(i)) {
  547. // The higher the index, the more expired the lease.
  548. expire(i, 10 + i);
  549. }
  550. }
  551. // Run leases reclamation routine on all leases. This should result
  552. // in setting "expired-reclaimed" state for all leases with even
  553. // indexes.
  554. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, false));
  555. // Leases with even indexes should be marked as reclaimed.
  556. EXPECT_TRUE(testLeases(&leaseReclaimed, &evenLeaseIndex));
  557. // Leases with odd indexes shouldn't be marked as reclaimed.
  558. EXPECT_TRUE(testLeases(&leaseNotReclaimed, &oddLeaseIndex));
  559. }
  560. /// @brief Test that the leases may be reclaimed by being deleted.
  561. void testReclaimExpiredLeasesDelete() {
  562. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  563. // Mark leases with even indexes as expired.
  564. if (evenLeaseIndex(i)) {
  565. // The higher the index, the more expired the lease.
  566. expire(i, 10 + i);
  567. }
  568. }
  569. // Run leases reclamation routine on all leases. This should result
  570. // in removal of all leases with even indexes.
  571. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, true));
  572. // Leases with odd indexes should be retained and their state
  573. // shouldn't be "expired-reclaimed".
  574. EXPECT_TRUE(testLeases(&leaseNotReclaimed, &oddLeaseIndex));
  575. // Leases with even indexes should have been removed.
  576. EXPECT_TRUE(testLeases(&leaseDoesntExist, &evenLeaseIndex));
  577. }
  578. /// @brief Test that it is possible to specify the limit for the number
  579. /// of reclaimed leases.
  580. void testReclaimExpiredLeasesLimit() {
  581. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  582. // Mark all leaes as expired. The higher the index the less
  583. // expired the lease.
  584. expire(i, 1000 - i);
  585. }
  586. // We will be performing lease reclamation on lease groups of 10.
  587. // Hence, it is convenient if the number of test leases is a
  588. // multiple of 10.
  589. const size_t reclamation_group_size = 10;
  590. BOOST_STATIC_ASSERT(TEST_LEASES_NUM % reclamation_group_size == 0);
  591. // Leases will be reclaimed in groups of 10.
  592. for (unsigned int i = reclamation_group_size; i < TEST_LEASES_NUM;
  593. i += reclamation_group_size) {
  594. // Reclaim 10 most expired leases out of TEST_LEASES_NUM. Since
  595. // leases are ordered from the most expired to the least expired
  596. // this should reclaim leases between 0 and 9, then 10 and 19 etc.
  597. ASSERT_NO_THROW(reclaimExpiredLeases(reclamation_group_size,
  598. 0, false));
  599. // Check that leases having all indexes between 0 and 9, 19, 29 etc.
  600. // have been reclaimed.
  601. EXPECT_TRUE(testLeases(&leaseReclaimed, &allLeaseIndexes,
  602. LowerBound(0), UpperBound(i)))
  603. << "check failed for i = " << i;
  604. // Check that all remaining leases haven't been reclaimed.
  605. EXPECT_TRUE(testLeases(&leaseNotReclaimed, &allLeaseIndexes,
  606. LowerBound(i), UpperBound(TEST_LEASES_NUM)))
  607. << "check failed for i = " << i;
  608. }
  609. }
  610. /// @brief Test that DNS updates are generated for the leases for which
  611. /// the DNS records exist.
  612. void testReclaimExpiredLeasesWithDDNS() {
  613. // DNS must be started for the D2 client to accept NCRs.
  614. ASSERT_NO_THROW(enableDDNS());
  615. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  616. // Expire all leases with even indexes.
  617. if (evenLeaseIndex(i)) {
  618. // The higher the index, the more expired the lease.
  619. expire(i, 10 + i);
  620. }
  621. }
  622. // Reclaim all expired leases.
  623. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, false));
  624. // Leases with odd indexes shouldn't be reclaimed.
  625. EXPECT_TRUE(testLeases(&leaseNotReclaimed, &oddLeaseIndex));
  626. // Leases with even indexes should be reclaimed.
  627. EXPECT_TRUE(testLeases(&leaseReclaimed, &evenLeaseIndex));
  628. // DNS updates (removal NCRs) should be generated for leases with even
  629. // indexes.
  630. EXPECT_TRUE(testLeases(&dnsUpdateGeneratedForLease, &evenLeaseIndex));
  631. // DNS updates (removal NCRs) shouldn't be generated for leases with
  632. // odd indexes.
  633. EXPECT_TRUE(testLeases(&dnsUpdateNotGeneratedForLease, &oddLeaseIndex));
  634. }
  635. /// @brief Test that DNS updates are only generated for the reclaimed
  636. /// leases (not for all leases with hostname stored).
  637. void testReclaimExpiredLeasesWithDDNSAndLimit() {
  638. // DNS must be started for the D2 client to accept NCRs.
  639. ASSERT_NO_THROW(enableDDNS());
  640. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  641. // Expire only leases with even indexes.
  642. if (evenLeaseIndex(i)) {
  643. // The higher the index, the more expired the lease.
  644. expire(i, 10 + i);
  645. }
  646. }
  647. const size_t reclamation_group_size = 10;
  648. BOOST_STATIC_ASSERT(TEST_LEASES_NUM % reclamation_group_size == 0);
  649. // Leases will be reclaimed in groups of 10
  650. for (unsigned int i = 10; i < TEST_LEASES_NUM; i += reclamation_group_size) {
  651. // Reclaim 10 most expired leases. Note that the leases with the
  652. // higher index are more expired. For example, if the
  653. // TEST_LEASES_NUM is equal to 100, the most expired lease will
  654. // be 98, then 96, 94 etc.
  655. ASSERT_NO_THROW(reclaimExpiredLeases(reclamation_group_size, 0,
  656. false));
  657. // After the first iteration the lower bound is 80, because there
  658. // will be 10 the most expired leases in this group: 80, 82, 84,
  659. // 86, 88, 90, 92, 94, 96, 98. For subsequent iterations
  660. // accordingly.
  661. int reclaimed_lower_bound = TEST_LEASES_NUM - 2 * i;
  662. // At some point the lower bound will hit the negative value, which
  663. // must be corrected to 0.
  664. if (reclaimed_lower_bound < 0) {
  665. reclaimed_lower_bound = 0;
  666. }
  667. // Leases between the lower bound calculated above and the upper
  668. // bound of all leases, and having even indexes should have been
  669. // reclaimed.
  670. EXPECT_TRUE(testLeases(&leaseReclaimed, &evenLeaseIndex,
  671. LowerBound(reclaimed_lower_bound),
  672. UpperBound(TEST_LEASES_NUM)))
  673. << "check failed for i = " << i;
  674. // For the same leases we should have generated DNS updates
  675. // (removal NCRs).
  676. EXPECT_TRUE(testLeases(&dnsUpdateGeneratedForLease, &evenLeaseIndex,
  677. LowerBound(reclaimed_lower_bound),
  678. UpperBound(TEST_LEASES_NUM)))
  679. << "check failed for i = " << i;
  680. // Leases with odd indexes (falling between the reclaimed ones)
  681. // shouldn't have been reclaimed, because they are not expired.
  682. EXPECT_TRUE(testLeases(&leaseNotReclaimed, &oddLeaseIndex,
  683. LowerBound(reclaimed_lower_bound),
  684. UpperBound(TEST_LEASES_NUM)))
  685. << "check failed for i = " << i;
  686. EXPECT_TRUE(testLeases(&dnsUpdateNotGeneratedForLease,
  687. &oddLeaseIndex,
  688. LowerBound(reclaimed_lower_bound),
  689. UpperBound(TEST_LEASES_NUM)))
  690. << "check failed for i = " << i;
  691. // At early stages of iterations, there should be conitnuous
  692. // group of leases (expired and not expired) which haven't been
  693. // reclaimed.
  694. if (reclaimed_lower_bound > 0) {
  695. EXPECT_TRUE(testLeases(&leaseNotReclaimed, &allLeaseIndexes,
  696. LowerBound(0),
  697. UpperBound(reclaimed_lower_bound)))
  698. << "check failed for i = " << i;
  699. EXPECT_TRUE(testLeases(&dnsUpdateNotGeneratedForLease,
  700. &oddLeaseIndex,
  701. LowerBound(0),
  702. UpperBound(reclaimed_lower_bound)));
  703. }
  704. }
  705. }
  706. /// @brief This test verifies that reclamation routine continues if the
  707. /// DNS update has failed for some leases.
  708. void testReclaimExpiredLeasesInvalidHostname() {
  709. // DNS must be started for the D2 client to accept NCRs.
  710. ASSERT_NO_THROW(enableDDNS());
  711. for (size_t i = 0; i < TEST_LEASES_NUM; ++i) {
  712. // Generate invalid hostname for every other lease.
  713. if (evenLeaseIndex(i)) {
  714. // Hostname with two consecutive dots is invalid and may result
  715. // in exception if the reclamation routine doesn't protect
  716. // aginst such exceptions.
  717. std::ostringstream hostname_s;
  718. hostname_s << "invalid-host" << i << "..example.com";
  719. leases_[i]->hostname_ = hostname_s.str();
  720. ASSERT_NO_THROW(updateLease(i));
  721. }
  722. // Every lease is expired.
  723. expire(i, 10 + i);
  724. }
  725. // Although we know that some hostnames are broken we don't want the
  726. // reclamation process to break when it finds a broken record.
  727. // It should rather continue to process other leases.
  728. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, false));
  729. // All leases should have been reclaimed. Broken DNS entry doesn't
  730. // warrant that we don't reclaim the lease.
  731. EXPECT_TRUE(testLeases(&leaseReclaimed, &allLeaseIndexes));
  732. // The routine should not generate DNS updates for the leases with
  733. // broken hostname.
  734. EXPECT_TRUE(testLeases(&dnsUpdateNotGeneratedForLease,
  735. &evenLeaseIndex));
  736. // But it should generate DNS updates for the leases with the correct
  737. // hostname.
  738. EXPECT_TRUE(testLeases(&dnsUpdateGeneratedForLease, &oddLeaseIndex));
  739. }
  740. /// @brief This test verfies that callouts are executed for each expired
  741. /// lease when installed.
  742. void testReclaimExpiredLeasesHooks() {
  743. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  744. if (evenLeaseIndex(i)) {
  745. expire(i, 1000 - i);
  746. }
  747. }
  748. vector<string> libraries; // no libraries at this time
  749. HooksManager::loadLibraries(libraries);
  750. // Install a callout: lease4_expire or lease6_expire.
  751. std::ostringstream callout_name;
  752. callout_name << callout_argument_name << "_expire";
  753. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  754. callout_name.str(), leaseExpireCallout));
  755. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, false));
  756. // Callouts should be executed for leases with even indexes and these
  757. // leases should be reclaimed.
  758. EXPECT_TRUE(testLeases(&leaseCalloutExecuted, &evenLeaseIndex));
  759. EXPECT_TRUE(testLeases(&leaseReclaimed, &evenLeaseIndex));
  760. // Callouts should not be executed for leases with odd indexes and these
  761. // leases should not be reclaimed.
  762. EXPECT_TRUE(testLeases(&leaseCalloutNotExecuted, &oddLeaseIndex));
  763. EXPECT_TRUE(testLeases(&leaseNotReclaimed, &oddLeaseIndex));
  764. }
  765. /// @brief This test verfies that callouts are executed for each expired
  766. /// lease and that the lease is not reclaimed when skip flag is set.
  767. void testReclaimExpiredLeasesHooksWithSkip() {
  768. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  769. if (evenLeaseIndex(i)) {
  770. expire(i, 1000 - i);
  771. }
  772. }
  773. vector<string> libraries; // no libraries at this time
  774. HooksManager::loadLibraries(libraries);
  775. // Install a callout: lease4_expire or lease6_expire.
  776. std::ostringstream callout_name;
  777. callout_name << callout_argument_name << "_expire";
  778. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  779. callout_name.str(), leaseExpireWithSkipCallout));
  780. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, false));
  781. // Callouts should have been executed for leases with even indexes.
  782. EXPECT_TRUE(testLeases(&leaseCalloutExecuted, &evenLeaseIndex));
  783. // Callouts should not be executed for leases with odd indexes.
  784. EXPECT_TRUE(testLeases(&leaseCalloutNotExecuted, &oddLeaseIndex));
  785. // Leases shouldn't be reclaimed because the callout sets the
  786. // skip flag for each of them.
  787. EXPECT_TRUE(testLeases(&leaseNotReclaimed, &allLeaseIndexes));
  788. }
  789. /// @brief This test verifies that it is possible to set the timeout for
  790. /// the execution of the lease reclamation routine.
  791. void testReclaimExpiredLeasesTimeout(const uint16_t timeout) {
  792. // Leases are segregated from the most expired to the least expired.
  793. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  794. expire(i, 2000 - i);
  795. }
  796. vector<string> libraries;
  797. HooksManager::loadLibraries(libraries);
  798. // Install a callout: lease4_expire or lease6_expire. Each callout
  799. // takes at least 40ms to run (it uses usleep).
  800. std::ostringstream callout_name;
  801. callout_name << callout_argument_name << "_expire";
  802. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  803. callout_name.str(), leaseExpireWithDelayCallout));
  804. // Reclaim leases with timeout.
  805. ASSERT_NO_THROW(reclaimExpiredLeases(0, timeout, false));
  806. // We reclaimed at most (timeout / 40ms) leases.
  807. const uint16_t theoretical_reclaimed = static_cast<uint16_t>(timeout / 40);
  808. // The actual number of leases reclaimed is likely to be lower than
  809. // the theoretical number. For low theoretical number the adjusted
  810. // number is always 1. For higher number, it will be 10 less than the
  811. // theoretical number.
  812. const uint16_t adjusted_reclaimed = (theoretical_reclaimed > 10 ?
  813. theoretical_reclaimed - 10 : 1);
  814. EXPECT_TRUE(testLeases(&leaseCalloutExecuted, &allLeaseIndexes,
  815. LowerBound(0), UpperBound(adjusted_reclaimed)));
  816. EXPECT_TRUE(testLeases(&leaseReclaimed, &allLeaseIndexes,
  817. LowerBound(0), UpperBound(adjusted_reclaimed)));
  818. EXPECT_TRUE(testLeases(&leaseCalloutNotExecuted, &allLeaseIndexes,
  819. LowerBound(theoretical_reclaimed + 1),
  820. UpperBound(TEST_LEASES_NUM)));
  821. EXPECT_TRUE(testLeases(&leaseNotReclaimed, &allLeaseIndexes,
  822. LowerBound(theoretical_reclaimed + 1),
  823. UpperBound(TEST_LEASES_NUM)));
  824. }
  825. /// @brief This test verifies that expired-reclaimed leases are removed
  826. /// from the lease database.
  827. void testDeleteExpiredReclaimedLeases() {
  828. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  829. // Mark leases with even indexes as expired.
  830. if (evenLeaseIndex(i)) {
  831. // The higher the index, the more expired the lease.
  832. reclaim(i, 10 + i);
  833. }
  834. }
  835. // Run leases reclamation routine on all leases. This should result
  836. // in removal of all leases with even indexes.
  837. ASSERT_NO_THROW(deleteExpiredReclaimedLeases(10));
  838. // Leases with odd indexes shouldn't be removed from the database.
  839. EXPECT_TRUE(testLeases(&leaseExists, &oddLeaseIndex));
  840. // Leases with even indexes should have been removed.
  841. EXPECT_TRUE(testLeases(&leaseDoesntExist, &evenLeaseIndex));
  842. }
  843. /// @brief Test that declined expired leases can be removed.
  844. ///
  845. /// This method allows controlling remove_leases parameter when calling
  846. /// @ref AllocEngine::reclaimExpiredLeases4 or
  847. /// @ref AllocEngine::reclaimExpiredLeases6. This should not matter, as
  848. /// the address affinity doesn't make sense for declined leases (they don't
  849. /// have any useful information in them anymore), so AllocEngine should
  850. /// remove them all the time.
  851. ///
  852. /// @param remove see description above
  853. void testReclaimDeclined(bool remove) {
  854. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  855. // Mark leases with even indexes as expired.
  856. if (evenLeaseIndex(i)) {
  857. // Mark lease as declined with 100 seconds of probation-period
  858. // (i.e. lease is supposed to be off limits for 100 seconds)
  859. decline(i, 100);
  860. // The higher the index, the more expired the lease.
  861. expire(i, 10 + i);
  862. }
  863. }
  864. // Run leases reclamation routine on all leases. This should result
  865. // in removing all leases with status = declined, i.e. all
  866. // even leases should be gone.
  867. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, remove));
  868. // Leases with even indexes should not exist in the DB
  869. EXPECT_TRUE(testLeases(&leaseDoesntExist, &evenLeaseIndex));
  870. }
  871. /// @brief Test that appropriate statistics are updated when
  872. /// declined expired leases are processed by AllocEngine.
  873. ///
  874. /// This method works for both v4 and v6. Just make sure the correct
  875. /// statistic name is passed. This is the name of the assigned addresses,
  876. /// that is expected to be decreased once the reclaimation procedure
  877. /// is complete.
  878. ///
  879. /// @param stat_name name of the statistic for assigned addresses statistic
  880. /// ("assgined-addresses" for both v4 and "assigned-nas" for v6)
  881. void testReclaimDeclinedStats(const std::string& stat_name) {
  882. // Leases by default all belong to subnet_id_ = 1. Let's count the
  883. // number of declined leases.
  884. int subnet1_cnt = 0;
  885. int subnet2_cnt = 0;
  886. // Let's move all leases to declined,expired state.
  887. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  888. // Move the lease to declined state
  889. decline(i, 100);
  890. // And expire it, so it will be reclaimed
  891. expire(i, 10 + 1);
  892. // Move every other lease to subnet-id = 2.
  893. if (evenLeaseIndex(i)) {
  894. subnet1_cnt++;
  895. } else {
  896. subnet2_cnt++;
  897. setSubnetId(i, 2);
  898. }
  899. }
  900. StatsMgr& stats_mgr = StatsMgr::instance();
  901. // Let's set the global statistic. Values are arbitrary and can
  902. // be used to easily detect whether a given stat was decreased or
  903. // increased. They are sufficiently high compared to number of leases
  904. // to avoid any chances of going into negative.
  905. stats_mgr.setValue("declined-addresses", static_cast<int64_t>(1000));
  906. // Let's set global the counter for reclaimed declined addresses.
  907. stats_mgr.setValue("reclaimed-declined-addresses",
  908. static_cast<int64_t>(2000));
  909. // And those subnet specific as well
  910. stats_mgr.setValue(stats_mgr.generateName("subnet", 1,
  911. stat_name), int64_t(1000));
  912. stats_mgr.setValue(stats_mgr.generateName("subnet", 2,
  913. stat_name), int64_t(2000));
  914. stats_mgr.setValue(stats_mgr.generateName("subnet", 1,
  915. "reclaimed-declined-addresses"), int64_t(10000));
  916. stats_mgr.setValue(stats_mgr.generateName("subnet", 2,
  917. "reclaimed-declined-addresses"), int64_t(20000));
  918. stats_mgr.setValue(stats_mgr.generateName("subnet", 1,
  919. "declined-addresses"), int64_t(100));
  920. stats_mgr.setValue(stats_mgr.generateName("subnet", 2,
  921. "declined-addresses"), int64_t(200));
  922. // Run leases reclamation routine on all leases. This should result
  923. // in removal of all leases with even indexes.
  924. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, true));
  925. // Declined-addresses should be decreased from its initial value (1000)
  926. // for both recovered addresses from subnet1 and subnet2.
  927. testStatistics("declined-addresses", 1000 - subnet1_cnt - subnet2_cnt);
  928. // The code should bump up global counter for reclaimed declined
  929. // addresses.
  930. testStatistics("reclaimed-declined-addresses", 2000 + subnet1_cnt + subnet2_cnt);
  931. // subnet[X].assigned-addresses should go down. Between the time
  932. // of DHCPDECLINE(v4)/DECLINE(v6) reception and declined expired lease
  933. // reclaimation, we count this address as assigned-addresses. We decrease
  934. // assigned-addresses(v4)/assgined-nas(v6) when we reclaim the lease,
  935. // not when the packet is received. For explanation, see Duplicate
  936. // Addresses (DHCPDECLINE support) (v4) or Duplicate Addresses (DECLINE
  937. // support) sections in the User's Guide or a comment in
  938. // Dhcpv4Srv::declineLease or Dhcpv6Srv::declineLease.
  939. testStatistics("subnet[1]." + stat_name, 1000 - subnet1_cnt);
  940. testStatistics("subnet[2]." + stat_name, 2000 - subnet2_cnt);
  941. testStatistics("subnet[1].declined-addresses", 100 - subnet1_cnt);
  942. testStatistics("subnet[2].declined-addresses", 200 - subnet2_cnt);
  943. // subnet[X].reclaimed-declined-addresses should go up in each subnet
  944. testStatistics("subnet[1].reclaimed-declined-addresses", 10000 + subnet1_cnt);
  945. testStatistics("subnet[2].reclaimed-declined-addresses", 20000 + subnet1_cnt);
  946. }
  947. /// @brief Collection of leases created at construction time.
  948. std::vector<LeasePtrType> leases_;
  949. /// @brief Allocation engine instance used for tests.
  950. AllocEnginePtr engine_;
  951. };
  952. /// @brief Specialization of the @c ExpirationAllocEngineTest class to test
  953. /// reclamation of the IPv6 leases.
  954. class ExpirationAllocEngine6Test : public ExpirationAllocEngineTest<Lease6Ptr> {
  955. public:
  956. /// @brief Class constructor.
  957. ///
  958. /// This constructor initializes @c TEST_LEASES_NUM leases and
  959. /// stores them in the lease manager.
  960. ExpirationAllocEngine6Test();
  961. /// @brief Virtual destructor.
  962. ///
  963. /// Clears up static fields that may be modified by hooks.
  964. virtual ~ExpirationAllocEngine6Test() {
  965. callout_lease_.reset();
  966. callout_name_ = string("");
  967. }
  968. /// @brief Creates collection of leases for a test.
  969. ///
  970. /// It is called internally at the construction time.
  971. void createLeases();
  972. /// @brief Updates lease in the lease database.
  973. ///
  974. /// @param lease_index Index of the lease.
  975. virtual void updateLease(const unsigned int lease_index) {
  976. LeaseMgrFactory::instance().updateLease6(leases_[lease_index]);
  977. }
  978. /// @brief Sets subnet id for a lease.
  979. ///
  980. /// It also updates statistics of assigned leases in the stats manager.
  981. ///
  982. /// @param lease_index Lease index.
  983. /// @param id New subnet id.
  984. virtual void setSubnetId(const uint16_t lease_index, const SubnetID& id);
  985. /// @brief Sets type of a lease.
  986. ///
  987. /// It also updates statistics of assigned leases in the stats manager.
  988. ///
  989. /// @param lease_index Lease index.
  990. /// @param lease_type Lease type.
  991. void setLeaseType(const uint16_t lease_index, const Lease6::Type& lease_type);
  992. /// @brief Retrieves lease from the database.
  993. ///
  994. /// @param lease_index Index of the lease.
  995. virtual Lease6Ptr getLease(const unsigned int lease_index) const {
  996. return (LeaseMgrFactory::instance().getLease6(leases_[lease_index]->type_,
  997. leases_[lease_index]->addr_));
  998. }
  999. /// @brief Wrapper method running lease reclamation routine.
  1000. ///
  1001. /// @param max_leases Maximum number of leases to be reclaimed.
  1002. /// @param timeout Maximum amount of time that the reclaimation routine
  1003. /// may be processing expired leases, expressed in seconds.
  1004. /// @param remove_lease A boolean value indicating if the lease should
  1005. /// be removed when it is reclaimed (if true) or it should be left in the
  1006. /// database in the "expired-reclaimed" state (if false).
  1007. virtual void reclaimExpiredLeases(const size_t max_leases,
  1008. const uint16_t timeout,
  1009. const bool remove_lease) {
  1010. engine_->reclaimExpiredLeases6(max_leases, timeout, remove_lease);
  1011. }
  1012. /// @brief Wrapper method for removing expired-reclaimed leases.
  1013. ///
  1014. /// @param secs The minimum amount of time, expressed in seconds,
  1015. /// for the lease to be left in the "expired-reclaimed" state
  1016. /// before it can be removed.
  1017. virtual void deleteExpiredReclaimedLeases(const uint32_t secs) {
  1018. engine_->deleteExpiredReclaimedLeases6(secs);
  1019. }
  1020. /// @brief Test that statistics is updated when leases are reclaimed.
  1021. void testReclaimExpiredLeasesStats();
  1022. /// @brief Callout for lease6_recover
  1023. ///
  1024. /// This callout stores passed parameter into static fields.
  1025. ///
  1026. /// @param callout_handle will be provided by hooks framework
  1027. /// @return always 0
  1028. static int lease6RecoverCallout(CalloutHandle& callout_handle) {
  1029. callout_name_ = "lease6_recover";
  1030. callout_handle.getArgument("lease6", callout_lease_);
  1031. return (0);
  1032. }
  1033. /// @brief Callout for lease6_recover that sets status to SKIP
  1034. ///
  1035. /// This callout stores passed parameter into static fields.
  1036. ///
  1037. /// @param callout_handle will be provided by hooks framework
  1038. /// @return always 0
  1039. static int lease6RecoverSkipCallout(CalloutHandle& callout_handle) {
  1040. // Set the next step status to SKIP
  1041. callout_handle.setStatus(CalloutHandle::NEXT_STEP_SKIP);
  1042. return (lease6RecoverCallout(callout_handle));
  1043. }
  1044. /// @brief Test install a hook callout, recovers declined leases
  1045. ///
  1046. /// This test: declines, then expires half of the leases, then
  1047. /// installs a callout on lease6_recover hook, then reclaims
  1048. /// expired leases and checks that:
  1049. /// - the callout was indeed called
  1050. /// - the parameter (lease6) was indeed passed as expected
  1051. /// - checks that the leases are removed (skip=false) or
  1052. /// - checks that the leases are still there (skip=true)
  1053. /// @param skip should the callout set the next step status to skip?
  1054. void
  1055. testReclaimDeclinedHook(bool skip);
  1056. /// The following parameters will be written by a callout
  1057. static std::string callout_name_; ///< Stores callout name
  1058. static Lease6Ptr callout_lease_; ///< Stores callout parameter
  1059. };
  1060. std::string ExpirationAllocEngine6Test::callout_name_;
  1061. Lease6Ptr ExpirationAllocEngine6Test::callout_lease_;
  1062. ExpirationAllocEngine6Test::ExpirationAllocEngine6Test()
  1063. : ExpirationAllocEngineTest<Lease6Ptr>("type=memfile universe=6 persist=false") {
  1064. createLeases();
  1065. callout_argument_name = "lease6";
  1066. // Let's clear any garbage previous test may have left in static fields.
  1067. callout_name_ = string("");
  1068. callout_lease_.reset();
  1069. }
  1070. void
  1071. ExpirationAllocEngine6Test::createLeases() {
  1072. // Create TEST_LEASES_NUM leases.
  1073. for (uint16_t i = 0; i < TEST_LEASES_NUM; ++i) {
  1074. // DUID
  1075. std::ostringstream duid_s;
  1076. duid_s << "01020304050607" << std::setw(4) << std::setfill('0') << i;
  1077. DuidPtr duid(new DUID(DUID::fromText(duid_s.str()).getDuid()));
  1078. // Address.
  1079. std::ostringstream address_s;
  1080. address_s << "2001:db8:1::" << std::setw(4) << std::setfill('0') << i;
  1081. IOAddress address(address_s.str());
  1082. // Create lease.
  1083. Lease6Ptr lease(new Lease6(Lease::TYPE_NA, address, duid, 1, 50, 60, 10,
  1084. 20, SubnetID(1), true, true,
  1085. generateHostnameForLeaseIndex(i)));
  1086. leases_.push_back(lease);
  1087. LeaseMgrFactory::instance().addLease(lease);
  1088. // Note in the statistics that this lease has been added.
  1089. StatsMgr& stats_mgr = StatsMgr::instance();
  1090. std::string stat_name =
  1091. lease->type_ == Lease::TYPE_NA ? "assigned-nas" : "assigned-pds";
  1092. stats_mgr.addValue(stats_mgr.generateName("subnet", lease->subnet_id_, stat_name),
  1093. int64_t(1));
  1094. }
  1095. }
  1096. void
  1097. ExpirationAllocEngine6Test::setSubnetId(const uint16_t lease_index, const SubnetID& id) {
  1098. ASSERT_GT(leases_.size(), lease_index);
  1099. if (leases_[lease_index]->subnet_id_ != id) {
  1100. StatsMgr& stats_mgr = StatsMgr::instance();
  1101. std::string stats_name = (leases_[lease_index]->type_ == Lease::TYPE_NA ?
  1102. "assigned-nas" : "assigned-pds");
  1103. stats_mgr.addValue(stats_mgr.generateName("subnet", id, stats_name),
  1104. int64_t(1));
  1105. stats_mgr.addValue(stats_mgr.generateName("subnet",
  1106. leases_[lease_index]->subnet_id_,
  1107. stats_name),
  1108. int64_t(-1));
  1109. leases_[lease_index]->subnet_id_ = id;
  1110. ASSERT_NO_THROW(updateLease(lease_index));
  1111. }
  1112. }
  1113. void
  1114. ExpirationAllocEngine6Test::setLeaseType(const uint16_t lease_index,
  1115. const Lease6::Type& lease_type) {
  1116. ASSERT_GT(leases_.size(), lease_index);
  1117. if (leases_[lease_index]->type_ != lease_type) {
  1118. StatsMgr& stats_mgr = StatsMgr::instance();
  1119. std::string stats_name = (lease_type == Lease::TYPE_NA ?
  1120. "assigned-nas" : "assigned-pds");
  1121. stats_mgr.addValue(stats_mgr.generateName("subnet",
  1122. leases_[lease_index]->subnet_id_,
  1123. stats_name),
  1124. int64_t(1));
  1125. stats_name = (leases_[lease_index]->type_ == Lease::TYPE_NA ?
  1126. "assigned-nas" : "assigned-pds");
  1127. stats_mgr.addValue(stats_mgr.generateName("subnet",
  1128. leases_[lease_index]->subnet_id_,
  1129. stats_name),
  1130. int64_t(-1));
  1131. leases_[lease_index]->type_ = lease_type;
  1132. ASSERT_NO_THROW(updateLease(lease_index));
  1133. }
  1134. }
  1135. void
  1136. ExpirationAllocEngine6Test::testReclaimExpiredLeasesStats() {
  1137. // This test requires that the number of leases is an even number.
  1138. BOOST_STATIC_ASSERT(TEST_LEASES_NUM % 2 == 0);
  1139. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  1140. // Mark all leaes as expired. The higher the index the less
  1141. // expired the lease.
  1142. expire(i, 1000 - i);
  1143. // Modify subnet ids and lease types for some leases.
  1144. if (evenLeaseIndex(i)) {
  1145. setSubnetId(i, SubnetID(2));
  1146. setLeaseType(i, Lease::TYPE_PD);
  1147. }
  1148. }
  1149. // Leases will be reclaimed in groups of 8.
  1150. const size_t reclamation_group_size = 8;
  1151. for (unsigned int i = reclamation_group_size; i < TEST_LEASES_NUM;
  1152. i += reclamation_group_size) {
  1153. // Reclaim 8 most expired leases out of TEST_LEASES_NUM.
  1154. ASSERT_NO_THROW(reclaimExpiredLeases(reclamation_group_size,
  1155. 0, false));
  1156. // Number of reclaimed leases should increase as we loop.
  1157. EXPECT_TRUE(testStatistics("reclaimed-leases", i));
  1158. // Make sure that the number of reclaimed leases is also distributed
  1159. // across two subnets.
  1160. EXPECT_TRUE(testStatistics("subnet[1].reclaimed-leases", i / 2));
  1161. EXPECT_TRUE(testStatistics("subnet[2].reclaimed-leases", i / 2));
  1162. // Number of assigned leases should decrease as we reclaim them.
  1163. EXPECT_TRUE(testStatistics("subnet[1].assigned-nas",
  1164. (TEST_LEASES_NUM - i) / 2));
  1165. EXPECT_TRUE(testStatistics("subnet[2].assigned-pds",
  1166. (TEST_LEASES_NUM - i) / 2));
  1167. }
  1168. }
  1169. void
  1170. ExpirationAllocEngine6Test::testReclaimDeclinedHook(bool skip) {
  1171. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  1172. // Mark leases with even indexes as expired.
  1173. if (evenLeaseIndex(i)) {
  1174. // Mark lease as declined with 100 seconds of probation-period
  1175. // (i.e. lease is supposed to be off limits for 100 seconds)
  1176. decline(i, 100);
  1177. // The higher the index, the more expired the lease.
  1178. expire(i, 10 + i);
  1179. }
  1180. }
  1181. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1182. "lease6_recover",
  1183. skip ? lease6RecoverSkipCallout : lease6RecoverCallout));
  1184. // Run leases reclamation routine on all leases.
  1185. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, true));
  1186. // Make sure that the callout really was called. It was supposed to modify
  1187. // the callout_name_ and store the lease in callout_lease_
  1188. EXPECT_EQ("lease6_recover", callout_name_);
  1189. EXPECT_TRUE(callout_lease_);
  1190. // Leases with even indexes should not exist in the DB
  1191. if (skip) {
  1192. // Skip status should have prevented removing the lease.
  1193. EXPECT_TRUE(testLeases(&leaseExists, &evenLeaseIndex));
  1194. } else {
  1195. // The hook hasn't modified next step status. The lease should be gone.
  1196. EXPECT_TRUE(testLeases(&leaseDoesntExist, &evenLeaseIndex));
  1197. }
  1198. };
  1199. // This test verifies that the leases can be reclaimed without being removed
  1200. // from the database. In such case, the leases' state is set to
  1201. // "expired-reclaimed".
  1202. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeases6UpdateState) {
  1203. testReclaimExpiredLeasesUpdateState();
  1204. }
  1205. // This test verifies that the reclaimed leases are deleted when requested.
  1206. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesDelete) {
  1207. testReclaimExpiredLeasesDelete();
  1208. }
  1209. // This test verifies that it is possible to specify the limit for the
  1210. // number of reclaimed leases.
  1211. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesLimit) {
  1212. testReclaimExpiredLeasesLimit();
  1213. }
  1214. // This test verifies that DNS updates are generated for the leases
  1215. // for which the DNS records exist.
  1216. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesWithDDNS) {
  1217. testReclaimExpiredLeasesWithDDNS();
  1218. }
  1219. // This test verifies that it is DNS updates are generated only for the
  1220. // reclaimed expired leases. In this case we limit the number of leases
  1221. // reclaimed during a single call to reclamation routine.
  1222. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesWithDDNSAndLimit) {
  1223. testReclaimExpiredLeasesWithDDNSAndLimit();
  1224. }
  1225. // This test verifies that if some leases have invalid hostnames, the
  1226. // lease reclamation routine continues with reclamation of leases anyway.
  1227. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesInvalidHostname) {
  1228. testReclaimExpiredLeasesInvalidHostname();
  1229. }
  1230. // This test verifies that statistics is correctly updated when the leases
  1231. // are reclaimed.
  1232. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesStats) {
  1233. testReclaimExpiredLeasesStats();
  1234. }
  1235. // This test verifies that callouts are executed for each expired lease.
  1236. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesHooks) {
  1237. testReclaimExpiredLeasesHooks();
  1238. }
  1239. // This test verifies that callouts are executed for each expired lease
  1240. // and that the lease is not reclaimed when the skip flag is set.
  1241. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesHooksWithSkip) {
  1242. testReclaimExpiredLeasesHooksWithSkip();
  1243. }
  1244. // This test verifies that it is possible to set the timeout for the
  1245. // execution of the lease reclamation routine.
  1246. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesTimeout) {
  1247. // This test needs at least 40 leases to make sense.
  1248. BOOST_STATIC_ASSERT(TEST_LEASES_NUM >= 40);
  1249. // Run with timeout of 1.2s.
  1250. testReclaimExpiredLeasesTimeout(1200);
  1251. }
  1252. // This test verifies that at least one lease is reclaimed if the timeout
  1253. // for the lease reclamation routine is shorter than the time needed for
  1254. // the reclamation of a single lease. This prevents the situation when
  1255. // very short timeout (perhaps misconfigured) effectively precludes leases
  1256. // reclamation.
  1257. TEST_F(ExpirationAllocEngine6Test, reclaimExpiredLeasesShortTimeout) {
  1258. // We will most likely reclaim just one lease, so 5 is more than enough.
  1259. BOOST_STATIC_ASSERT(TEST_LEASES_NUM >= 5);
  1260. // Reclaim leases with the 1ms timeout.
  1261. testReclaimExpiredLeasesTimeout(1);
  1262. }
  1263. // This test verifies that expired-reclaimed leases are removed from the
  1264. // lease database.
  1265. TEST_F(ExpirationAllocEngine6Test, deleteExpiredReclaimedLeases) {
  1266. BOOST_STATIC_ASSERT(TEST_LEASES_NUM >= 10);
  1267. testDeleteExpiredReclaimedLeases();
  1268. }
  1269. /// This test verifies that @ref AllocEngine::reclaimExpiredLeases6 properly
  1270. /// handles declined leases that have expired in case when it is told to
  1271. /// remove leases.}
  1272. TEST_F(ExpirationAllocEngine6Test, reclaimDeclined1) {
  1273. testReclaimDeclined(true);
  1274. }
  1275. /// This test verifies that @ref AllocEngine::reclaimExpiredLeases6 properly
  1276. /// handles declined leases that have expired in case when it is told to
  1277. /// not remove leases. This flag should not matter and declined expired
  1278. /// leases should always be removed.
  1279. TEST_F(ExpirationAllocEngine6Test, reclaimDeclined2) {
  1280. testReclaimDeclined(false);
  1281. }
  1282. /// This test verifies that statistics are modified correctly after
  1283. /// reclaim expired leases is called.
  1284. TEST_F(ExpirationAllocEngine6Test, reclaimDeclinedStats) {
  1285. testReclaimDeclinedStats("assigned-nas");
  1286. }
  1287. // This test verifies if the hooks installed on lease6_recover are called
  1288. // when the lease expires.
  1289. TEST_F(ExpirationAllocEngine6Test, reclaimDeclinedHook1) {
  1290. testReclaimDeclinedHook(false); // false = don't use skip callout
  1291. }
  1292. // This test verifies if the hooks installed on lease6_recover are called
  1293. // when the lease expires and that the next step status set to SKIP
  1294. // causes the recovery to not be conducted.
  1295. TEST_F(ExpirationAllocEngine6Test, reclaimDeclinedHook2) {
  1296. testReclaimDeclinedHook(true); // true = use skip callout
  1297. }
  1298. // *******************************************************
  1299. //
  1300. // DHCPv4 lease reclamation routine tests start here!
  1301. //
  1302. // *******************************************************
  1303. /// @brief Specialization of the @c ExpirationAllocEngineTest class to test
  1304. /// reclamation of the IPv4 leases.
  1305. class ExpirationAllocEngine4Test : public ExpirationAllocEngineTest<Lease4Ptr> {
  1306. public:
  1307. /// @brief Class constructor.
  1308. ///
  1309. /// This constructor initializes @c TEST_LEASES_NUM leases and
  1310. /// stores them in the lease manager.
  1311. ExpirationAllocEngine4Test();
  1312. /// @brief Virtual destructor.
  1313. ///
  1314. /// Clears up static fields that may be modified by hooks.
  1315. virtual ~ExpirationAllocEngine4Test() {
  1316. callout_lease_.reset();
  1317. callout_name_ = string("");
  1318. }
  1319. /// @brief Creates collection of leases for a test.
  1320. ///
  1321. /// It is called internally at the construction time.
  1322. void createLeases();
  1323. /// @brief Generates unique client identifier from lease index.
  1324. ///
  1325. /// @param index lease index.
  1326. void setUniqueClientId(const uint16_t index);
  1327. /// @brief Updates lease in the lease database.
  1328. ///
  1329. /// @param lease_index Index of the lease.
  1330. virtual void updateLease(const unsigned int lease_index) {
  1331. LeaseMgrFactory::instance().updateLease4(leases_[lease_index]);
  1332. }
  1333. /// @brief Retrieves lease from the database.
  1334. ///
  1335. /// @param lease_index Index of the lease.
  1336. virtual Lease4Ptr getLease(const unsigned int lease_index) const {
  1337. return (LeaseMgrFactory::instance().getLease4(leases_[lease_index]->addr_));
  1338. }
  1339. /// @brief Sets subnet id for a lease.
  1340. ///
  1341. /// It also updates statistics of assigned leases in the stats manager.
  1342. ///
  1343. /// @param lease_index Lease index.
  1344. /// @param id New subnet id.
  1345. virtual void setSubnetId(const uint16_t lease_index, const SubnetID& id);
  1346. /// @brief Wrapper method running lease reclamation routine.
  1347. ///
  1348. /// @param max_leases Maximum number of leases to be reclaimed.
  1349. /// @param timeout Maximum amount of time that the reclaimation routine
  1350. /// may be processing expired leases, expressed in seconds.
  1351. /// @param remove_lease A boolean value indicating if the lease should
  1352. /// be removed when it is reclaimed (if true) or it should be left in the
  1353. /// database in the "expired-reclaimed" state (if false).
  1354. virtual void reclaimExpiredLeases(const size_t max_leases,
  1355. const uint16_t timeout,
  1356. const bool remove_lease) {
  1357. engine_->reclaimExpiredLeases4(max_leases, timeout, remove_lease);
  1358. }
  1359. /// @brief Wrapper method for removing expired-reclaimed leases.
  1360. ///
  1361. /// @param secs The minimum amount of time, expressed in seconds,
  1362. /// for the lease to be left in the "expired-reclaimed" state
  1363. /// before it can be removed.
  1364. virtual void deleteExpiredReclaimedLeases(const uint32_t secs) {
  1365. engine_->deleteExpiredReclaimedLeases4(secs);
  1366. }
  1367. /// @brief Lease algorithm checking if NCR has been generated from client
  1368. /// identifier.
  1369. ///
  1370. /// @param lease Pointer to the lease for which the NCR needs to be checked.
  1371. static bool dnsUpdateGeneratedFromClientId(const Lease4Ptr& lease);
  1372. /// @brief Lease algorithm checking if NCR has been generated from
  1373. /// HW address.
  1374. static bool dnsUpdateGeneratedFromHWAddress(const Lease4Ptr& lease);
  1375. /// @brief Test that DNS updates are properly generated when the
  1376. /// reclaimed leases contain client identifier.
  1377. void testReclaimExpiredLeasesWithDDNSAndClientId();
  1378. /// @brief Test that statistics is updated when leases are reclaimed..
  1379. void testReclaimExpiredLeasesStats();
  1380. /// @brief Callout for lease4_recover
  1381. ///
  1382. /// This callout stores passed parameter into static fields.
  1383. ///
  1384. /// @param callout_handle will be provided by hooks framework
  1385. /// @return always 0
  1386. static int lease4RecoverCallout(CalloutHandle& callout_handle) {
  1387. callout_name_ = "lease4_recover";
  1388. callout_handle.getArgument("lease4", callout_lease_);
  1389. return (0);
  1390. }
  1391. /// @brief Callout for lease4_recover that sets status to SKIP
  1392. ///
  1393. /// This callout stores passed parameter into static fields.
  1394. ///
  1395. /// @param callout_handle will be provided by hooks framework
  1396. /// @return always 0
  1397. static int lease4RecoverSkipCallout(CalloutHandle& callout_handle) {
  1398. // Set the next step status to SKIP
  1399. callout_handle.setStatus(CalloutHandle::NEXT_STEP_SKIP);
  1400. return (lease4RecoverCallout(callout_handle));
  1401. }
  1402. /// @brief Test install a hook callout, recovers declined leases
  1403. ///
  1404. /// This test: declines, then expires half of the leases, then
  1405. /// installs a callout on lease4_recover hook, then reclaims
  1406. /// expired leases and checks that:
  1407. /// - the callout was indeed called
  1408. /// - the parameter (lease4) was indeed passed as expected
  1409. /// - checks that the leases are removed (skip=false) or
  1410. /// - checks that the leases are still there (skip=true)
  1411. /// @param skip should the callout set the next step status to skip?
  1412. void
  1413. testReclaimDeclinedHook(bool skip);
  1414. /// The following parameters will be written by a callout
  1415. static std::string callout_name_; ///< Stores callout name
  1416. static Lease4Ptr callout_lease_; ///< Stores callout parameter
  1417. };
  1418. std::string ExpirationAllocEngine4Test::callout_name_;
  1419. Lease4Ptr ExpirationAllocEngine4Test::callout_lease_;
  1420. ExpirationAllocEngine4Test::ExpirationAllocEngine4Test()
  1421. : ExpirationAllocEngineTest<Lease4Ptr>("type=memfile universe=4 persist=false") {
  1422. createLeases();
  1423. callout_argument_name = "lease4";
  1424. // Let's clear any garbage previous test may have left in static fields.
  1425. callout_name_ = string("");
  1426. callout_lease_.reset();
  1427. }
  1428. void
  1429. ExpirationAllocEngine4Test::createLeases() {
  1430. // Create TEST_LEASES_NUM leases.
  1431. for (uint16_t i = 0; i < TEST_LEASES_NUM; ++i) {
  1432. // HW address
  1433. std::ostringstream hwaddr_s;
  1434. hwaddr_s << "01:02:03:04:" << std::setw(2) << std::setfill('0')
  1435. << (i >> 8) << ":" << std::setw(2) << std::setfill('0')
  1436. << (i & 0x00FF);
  1437. HWAddrPtr hwaddr(new HWAddr(HWAddr::fromText(hwaddr_s.str(),
  1438. HTYPE_ETHER)));
  1439. // Address.
  1440. std::ostringstream address_s;
  1441. address_s << "10.0." << (i >> 8) << "." << (i & 0x00FF);
  1442. IOAddress address(address_s.str());
  1443. // Create lease.
  1444. Lease4Ptr lease(new Lease4(address, hwaddr, ClientIdPtr(), 60, 10, 20,
  1445. time(NULL), SubnetID(1), true, true,
  1446. generateHostnameForLeaseIndex(i)));
  1447. leases_.push_back(lease);
  1448. LeaseMgrFactory::instance().addLease(lease);
  1449. // Note in the statistics that this lease has been added.
  1450. StatsMgr& stats_mgr = StatsMgr::instance();
  1451. std::string stat_name = "assigned-addresses";
  1452. stats_mgr.addValue(stats_mgr.generateName("subnet", lease->subnet_id_, stat_name),
  1453. int64_t(1));
  1454. }
  1455. }
  1456. void
  1457. ExpirationAllocEngine4Test::setUniqueClientId(const uint16_t index) {
  1458. std::ostringstream clientid_s;
  1459. clientid_s << "AA:BB:" << std::setw(2) << std::setfill('0')
  1460. << (index >> 16) << ":" << std::setw(2) << std::setfill('0')
  1461. << (index & 0x00FF);
  1462. ClientIdPtr client_id(ClientId::fromText(clientid_s.str()));
  1463. leases_[index]->client_id_ = client_id;
  1464. LeaseMgrFactory::instance().updateLease4(leases_[index]);
  1465. }
  1466. void
  1467. ExpirationAllocEngine4Test::setSubnetId(const uint16_t lease_index, const SubnetID& id) {
  1468. ASSERT_GT(leases_.size(), lease_index);
  1469. if (leases_[lease_index]->subnet_id_ != id) {
  1470. StatsMgr& stats_mgr = StatsMgr::instance();
  1471. stats_mgr.addValue(stats_mgr.generateName("subnet", id, "assigned-addresses"),
  1472. int64_t(1));
  1473. stats_mgr.addValue(stats_mgr.generateName("subnet",
  1474. leases_[lease_index]->subnet_id_,
  1475. "assigned-addresses"),
  1476. int64_t(-1));
  1477. leases_[lease_index]->subnet_id_ = id;
  1478. ASSERT_NO_THROW(updateLease(lease_index));
  1479. }
  1480. }
  1481. bool
  1482. ExpirationAllocEngine4Test::dnsUpdateGeneratedFromClientId(const Lease4Ptr& lease) {
  1483. try {
  1484. NameChangeRequestPtr ncr = getNCRForLease(lease);
  1485. if (ncr) {
  1486. if (lease->client_id_) {
  1487. // Generate hostname for this lease. Note that the lease
  1488. // in the database doesn't have the hostname because it
  1489. // has been removed by the lease reclamation routine.
  1490. std::string hostname = generateHostnameForLeaseIndex(
  1491. getLeaseIndexFromAddress(lease->addr_));
  1492. // Get DHCID from NCR.
  1493. const D2Dhcid& dhcid = ncr->getDhcid();
  1494. // Generate reference DHCID to compare with the one from
  1495. // the NCR.
  1496. std::vector<uint8_t> fqdn_wire;
  1497. OptionDataTypeUtil::writeFqdn(hostname, fqdn_wire, true);
  1498. D2Dhcid clientid_dhcid(lease->client_id_->getClientId(),
  1499. fqdn_wire);
  1500. // Return true if they match.
  1501. return (dhcid == clientid_dhcid);
  1502. }
  1503. }
  1504. } catch (...) {
  1505. // If error occurred, treat it as no match.
  1506. return (false);
  1507. }
  1508. // All leases checked - no match.
  1509. return (false);
  1510. }
  1511. bool
  1512. ExpirationAllocEngine4Test::dnsUpdateGeneratedFromHWAddress(const Lease4Ptr& lease) {
  1513. try {
  1514. NameChangeRequestPtr ncr = getNCRForLease(lease);
  1515. if (ncr) {
  1516. if (lease->hwaddr_) {
  1517. // Generate hostname for this lease. Note that the lease
  1518. // in the database doesn't have the hostname because it
  1519. // has been removed by the lease reclamation routine.
  1520. std::string hostname = generateHostnameForLeaseIndex(
  1521. getLeaseIndexFromAddress(lease->addr_));
  1522. // Get DHCID from NCR.
  1523. const D2Dhcid& dhcid = ncr->getDhcid();
  1524. // Generate reference DHCID to compare with the one from
  1525. // the NCR.
  1526. std::vector<uint8_t> fqdn_wire;
  1527. OptionDataTypeUtil::writeFqdn(hostname, fqdn_wire, true);
  1528. D2Dhcid hwaddr_dhcid(lease->hwaddr_, fqdn_wire);
  1529. // Return true if they match.
  1530. return (dhcid == hwaddr_dhcid);
  1531. }
  1532. }
  1533. } catch (...) {
  1534. // If error occurred, treat it as no match.
  1535. return (false);
  1536. }
  1537. // All leases checked - no match.
  1538. return (false);
  1539. }
  1540. void
  1541. ExpirationAllocEngine4Test::testReclaimExpiredLeasesWithDDNSAndClientId() {
  1542. // DNS must be started for the D2 client to accept NCRs.
  1543. ASSERT_NO_THROW(enableDDNS());
  1544. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  1545. // Set client identifiers for leases with even indexes only.
  1546. if (evenLeaseIndex(i)) {
  1547. setUniqueClientId(i);
  1548. }
  1549. // Expire all leases. The higher the index, the more expired the lease.
  1550. expire(i, 10 + i);
  1551. }
  1552. // Reclaim all expired leases.
  1553. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, false));
  1554. // Leases with even indexes should be reclaimed.
  1555. EXPECT_TRUE(testLeases(&leaseReclaimed, &evenLeaseIndex));
  1556. // DNS updates (removal NCRs) should be generated for all leases.
  1557. EXPECT_TRUE(testLeases(&dnsUpdateGeneratedForLease, &allLeaseIndexes));
  1558. // Leases with even indexes include client identifiers so the DHCID should
  1559. // be generated from the client identifiers.
  1560. EXPECT_TRUE(testLeases(&dnsUpdateGeneratedFromClientId, &evenLeaseIndex));
  1561. // Leases with odd indexes do not include client identifiers so their
  1562. // DHCID should be generated from the HW address.
  1563. EXPECT_TRUE(testLeases(&dnsUpdateGeneratedFromHWAddress, &oddLeaseIndex));
  1564. }
  1565. void
  1566. ExpirationAllocEngine4Test::testReclaimExpiredLeasesStats() {
  1567. // This test requires that the number of leases is an even number.
  1568. BOOST_STATIC_ASSERT(TEST_LEASES_NUM % 2 == 0);
  1569. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  1570. // Mark all leaes as expired. The higher the index the less
  1571. // expired the lease.
  1572. expire(i, 1000 - i);
  1573. // Modify subnet ids of some leases.
  1574. if (evenLeaseIndex(i)) {
  1575. setSubnetId(i, 2);
  1576. }
  1577. }
  1578. // Leases will be reclaimed in groups of 8.
  1579. const size_t reclamation_group_size = 8;
  1580. for (unsigned int i = reclamation_group_size; i < TEST_LEASES_NUM;
  1581. i += reclamation_group_size) {
  1582. // Reclaim 8 most expired leases out of TEST_LEASES_NUM.
  1583. ASSERT_NO_THROW(reclaimExpiredLeases(reclamation_group_size,
  1584. 0, false));
  1585. // Number of reclaimed leases should increase as we loop.
  1586. EXPECT_TRUE(testStatistics("reclaimed-leases", i));
  1587. // Make sure that the number of reclaimed leases is also distributed
  1588. // across two subnets.
  1589. EXPECT_TRUE(testStatistics("subnet[1].reclaimed-leases", i / 2));
  1590. EXPECT_TRUE(testStatistics("subnet[2].reclaimed-leases", i / 2));
  1591. // Number of assigned leases should decrease as we reclaim them.
  1592. EXPECT_TRUE(testStatistics("subnet[1].assigned-addresses",
  1593. (TEST_LEASES_NUM - i) / 2));
  1594. EXPECT_TRUE(testStatistics("subnet[2].assigned-addresses",
  1595. (TEST_LEASES_NUM - i) / 2));
  1596. }
  1597. }
  1598. void
  1599. ExpirationAllocEngine4Test::testReclaimDeclinedHook(bool skip) {
  1600. for (unsigned int i = 0; i < TEST_LEASES_NUM; ++i) {
  1601. // Mark leases with even indexes as expired.
  1602. if (evenLeaseIndex(i)) {
  1603. // Mark lease as declined with 100 seconds of probation-period
  1604. // (i.e. lease is supposed to be off limits for 100 seconds)
  1605. decline(i, 100);
  1606. // The higher the index, the more expired the lease.
  1607. expire(i, 10 + i);
  1608. }
  1609. }
  1610. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1611. "lease4_recover",
  1612. skip ? lease4RecoverSkipCallout : lease4RecoverCallout));
  1613. // Run leases reclamation routine on all leases.
  1614. ASSERT_NO_THROW(reclaimExpiredLeases(0, 0, true));
  1615. // Make sure that the callout really was called. It was supposed to modify
  1616. // the callout_name_ and store the lease in callout_lease_
  1617. EXPECT_EQ("lease4_recover", callout_name_);
  1618. EXPECT_TRUE(callout_lease_);
  1619. // Leases with even indexes should not exist in the DB
  1620. if (skip) {
  1621. // Skip status should have prevented removing the lease.
  1622. EXPECT_TRUE(testLeases(&leaseExists, &evenLeaseIndex));
  1623. } else {
  1624. // The hook hasn't modified next step status. The lease should be gone.
  1625. EXPECT_TRUE(testLeases(&leaseDoesntExist, &evenLeaseIndex));
  1626. }
  1627. };
  1628. // This test verifies that the leases can be reclaimed without being removed
  1629. // from the database. In such case, the leases' state is set to
  1630. // "expired-reclaimed".
  1631. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesUpdateState) {
  1632. testReclaimExpiredLeasesUpdateState();
  1633. }
  1634. // This test verifies that the reclaimed leases are deleted when requested.
  1635. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesDelete) {
  1636. testReclaimExpiredLeasesDelete();
  1637. }
  1638. // This test verifies that it is possible to specify the limit for the
  1639. // number of reclaimed leases.
  1640. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesLimit) {
  1641. testReclaimExpiredLeasesLimit();
  1642. }
  1643. // This test verifies that DNS updates are generated for the leases
  1644. // for which the DNS records exist.
  1645. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesWithDDNS) {
  1646. testReclaimExpiredLeasesWithDDNS();
  1647. }
  1648. // This test verifies that it is DNS updates are generated only for the
  1649. // reclaimed expired leases. In this case we limit the number of leases
  1650. // reclaimed during a single call to reclamation routine.
  1651. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesWithDDNSAndLimit) {
  1652. testReclaimExpiredLeasesWithDDNSAndLimit();
  1653. }
  1654. // This test verifies that if some leases have invalid hostnames, the
  1655. // lease reclamation routine continues with reclamation of leases anyway.
  1656. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesInvalidHostname) {
  1657. testReclaimExpiredLeasesInvalidHostname();
  1658. }
  1659. // This test verifies that DNS updates are properly generated when the
  1660. // client id is used as a primary identifier in the lease.
  1661. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesWithDDNSAndClientId) {
  1662. testReclaimExpiredLeasesWithDDNSAndClientId();
  1663. }
  1664. // This test verifies that statistics is correctly updated when the leases
  1665. // are reclaimed.
  1666. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesStats) {
  1667. testReclaimExpiredLeasesStats();
  1668. }
  1669. // This test verifies that callouts are executed for each expired lease.
  1670. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesHooks) {
  1671. testReclaimExpiredLeasesHooks();
  1672. }
  1673. // This test verifies that callouts are executed for each expired lease
  1674. // and that the lease is not reclaimed when the skip flag is set.
  1675. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesHooksWithSkip) {
  1676. testReclaimExpiredLeasesHooksWithSkip();
  1677. }
  1678. // This test verifies that it is possible to set the timeout for the
  1679. // execution of the lease reclamation routine.
  1680. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesTimeout) {
  1681. // This test needs at least 40 leases to make sense.
  1682. BOOST_STATIC_ASSERT(TEST_LEASES_NUM >= 40);
  1683. // Run with timeout of 1.2s.
  1684. testReclaimExpiredLeasesTimeout(1200);
  1685. }
  1686. // This test verifies that at least one lease is reclaimed if the timeout
  1687. // for the lease reclamation routine is shorter than the time needed for
  1688. // the reclamation of a single lease. This prevents the situation when
  1689. // very short timeout (perhaps misconfigured) effectively precludes leases
  1690. // reclamation.
  1691. TEST_F(ExpirationAllocEngine4Test, reclaimExpiredLeasesShortTimeout) {
  1692. // We will most likely reclaim just one lease, so 5 is more than enough.
  1693. BOOST_STATIC_ASSERT(TEST_LEASES_NUM >= 5);
  1694. // Reclaim leases with the 1ms timeout.
  1695. testReclaimExpiredLeasesTimeout(1);
  1696. }
  1697. // This test verifies that expired-reclaimed leases are removed from the
  1698. // lease database.
  1699. TEST_F(ExpirationAllocEngine4Test, deleteExpiredReclaimedLeases) {
  1700. BOOST_STATIC_ASSERT(TEST_LEASES_NUM >= 10);
  1701. testDeleteExpiredReclaimedLeases();
  1702. }
  1703. /// This test verifies that @ref AllocEngine::reclaimExpiredLeases4 properly
  1704. /// handles declined leases that have expired in case when it is told to
  1705. /// remove leases.
  1706. TEST_F(ExpirationAllocEngine4Test, reclaimDeclined1) {
  1707. testReclaimDeclined(true);
  1708. }
  1709. /// This test verifies that @ref AllocEngine::reclaimExpiredLeases4 properly
  1710. /// handles declined leases that have expired in case when it is told to
  1711. /// not remove leases. This flag should not matter and declined expired
  1712. /// leases should always be removed.
  1713. TEST_F(ExpirationAllocEngine4Test, reclaimDeclined2) {
  1714. testReclaimDeclined(false);
  1715. }
  1716. /// This test verifies that statistics are modified correctly after
  1717. /// reclaim expired leases is called.
  1718. TEST_F(ExpirationAllocEngine4Test, reclaimDeclinedStats) {
  1719. testReclaimDeclinedStats("assigned-addresses");
  1720. }
  1721. // This test verifies if the hooks installed on lease4_recover are called
  1722. // when the lease expires.
  1723. TEST_F(ExpirationAllocEngine4Test, reclaimDeclinedHook1) {
  1724. testReclaimDeclinedHook(false); // false = don't use skip callout
  1725. }
  1726. // This test verifies if the hooks installed on lease4_recover are called
  1727. // when the lease expires and that the next step status set to SKIP
  1728. // causes the recovery to not be conducted.
  1729. TEST_F(ExpirationAllocEngine4Test, reclaimDeclinedHook2) {
  1730. testReclaimDeclinedHook(true); // true = use skip callout
  1731. }
  1732. }; // end of anonymous namespace