alloc_engine_expiration_unittest.cc 95 KB

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