alloc_engine_unittest.cc 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711
  1. // Copyright (C) 2012-2014 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <asiolink/io_address.h>
  16. #include <dhcp/duid.h>
  17. #include <dhcp/dhcp4.h>
  18. #include <dhcpsrv/alloc_engine.h>
  19. #include <dhcpsrv/cfgmgr.h>
  20. #include <dhcpsrv/host_mgr.h>
  21. #include <dhcpsrv/lease_mgr.h>
  22. #include <dhcpsrv/lease_mgr_factory.h>
  23. #include <dhcpsrv/memfile_lease_mgr.h>
  24. #include <dhcpsrv/tests/test_utils.h>
  25. #include <hooks/server_hooks.h>
  26. #include <hooks/callout_manager.h>
  27. #include <hooks/hooks_manager.h>
  28. #include <boost/shared_ptr.hpp>
  29. #include <boost/scoped_ptr.hpp>
  30. #include <gtest/gtest.h>
  31. #include <iostream>
  32. #include <sstream>
  33. #include <algorithm>
  34. #include <set>
  35. #include <time.h>
  36. using namespace std;
  37. using namespace isc;
  38. using namespace isc::asiolink;
  39. using namespace isc::hooks;
  40. using namespace isc::dhcp;
  41. using namespace isc::dhcp::test;
  42. namespace {
  43. /// @brief Allocation engine with some internal methods exposed
  44. class NakedAllocEngine : public AllocEngine {
  45. public:
  46. /// @brief the sole constructor
  47. /// @param engine_type specifies engine type (e.g. iterative)
  48. /// @param attempts number of lease selection attempts before giving up
  49. /// @param ipv6 specifies if the engine is IPv6 or IPv4
  50. NakedAllocEngine(AllocEngine::AllocType engine_type,
  51. unsigned int attempts, bool ipv6 = true)
  52. :AllocEngine(engine_type, attempts, ipv6) {
  53. }
  54. // Expose internal classes for testing purposes
  55. using AllocEngine::Allocator;
  56. using AllocEngine::IterativeAllocator;
  57. using AllocEngine::getAllocator;
  58. /// @brief IterativeAllocator with internal methods exposed
  59. class NakedIterativeAllocator: public AllocEngine::IterativeAllocator {
  60. public:
  61. /// @brief constructor
  62. /// @param type pool types that will be interated
  63. NakedIterativeAllocator(Lease::Type type)
  64. :IterativeAllocator(type) {
  65. }
  66. using AllocEngine::IterativeAllocator::increaseAddress;
  67. using AllocEngine::IterativeAllocator::increasePrefix;
  68. };
  69. };
  70. /// @brief Used in Allocation Engine tests for IPv6
  71. class AllocEngine6Test : public ::testing::Test {
  72. public:
  73. /// @brief Default constructor
  74. ///
  75. /// Sets duid_, iaid_, subnet_, pool_ fields to example values used
  76. /// in many tests, initializes cfg_mgr configuration and creates
  77. /// lease database.
  78. AllocEngine6Test() {
  79. CfgMgr::instance().clear();
  80. duid_ = DuidPtr(new DUID(vector<uint8_t>(8, 0x42)));
  81. iaid_ = 42;
  82. // Initialize a subnet and short address pool.
  83. initSubnet(IOAddress("2001:db8:1::"),
  84. IOAddress("2001:db8:1::10"),
  85. IOAddress("2001:db8:1::20"));
  86. initFqdn("", false, false);
  87. factory_.create("type=memfile universe=6 persist=false");
  88. }
  89. /// @brief Configures a subnet and adds one pool to it.
  90. ///
  91. /// This function removes existing v6 subnets before configuring
  92. /// a new one.
  93. ///
  94. /// @param subnet Address of a subnet to be configured.
  95. /// @param pool_start First address in the address pool.
  96. /// @param pool_end Last address in the address pool.
  97. void initSubnet(const IOAddress& subnet, const IOAddress& pool_start,
  98. const IOAddress& pool_end) {
  99. CfgMgr& cfg_mgr = CfgMgr::instance();
  100. subnet_ = Subnet6Ptr(new Subnet6(subnet, 56, 1, 2, 3, 4));
  101. pool_ = Pool6Ptr(new Pool6(Lease::TYPE_NA, pool_start, pool_end));
  102. subnet_->addPool(pool_);
  103. pd_pool_ = Pool6Ptr(new Pool6(Lease::TYPE_PD, subnet, 56, 64));
  104. subnet_->addPool(pd_pool_);
  105. cfg_mgr.getStagingCfg()->getCfgSubnets6()->add(subnet_);
  106. cfg_mgr.commit();
  107. }
  108. /// @brief Initializes FQDN data for a test.
  109. ///
  110. /// The initialized values are used by the test fixture class members to
  111. /// verify the correctness of a lease.
  112. ///
  113. /// @param hostname Hostname to be assigned to a lease.
  114. /// @param fqdn_fwd Indicates whether or not to perform forward DNS update
  115. /// for a lease.
  116. /// @param fqdn_fwd Indicates whether or not to perform reverse DNS update
  117. /// for a lease.
  118. void initFqdn(const std::string& hostname, const bool fqdn_fwd,
  119. const bool fqdn_rev) {
  120. hostname_ = hostname;
  121. fqdn_fwd_ = fqdn_fwd;
  122. fqdn_rev_ = fqdn_rev;
  123. }
  124. /// @brief attempts to convert leases collection to a single lease
  125. ///
  126. /// This operation makes sense if there is at most one lease in the
  127. /// collection. Otherwise it will throw.
  128. ///
  129. /// @param col collection of leases (zero or one leases allowed)
  130. /// @throw MultipleRecords if there is more than one lease
  131. /// @return Lease6 pointer (or NULL if collection was empty)
  132. Lease6Ptr expectOneLease(const Lease6Collection& col) {
  133. if (col.size() > 1) {
  134. isc_throw(MultipleRecords, "More than one lease found in collection");
  135. }
  136. if (col.empty()) {
  137. return (Lease6Ptr());
  138. }
  139. return (*col.begin());
  140. }
  141. /// @brief checks if Lease6 matches expected configuration
  142. ///
  143. /// @param lease lease to be checked
  144. /// @param exp_type expected lease type
  145. /// @param exp_pd_len expected prefix length
  146. void checkLease6(const Lease6Ptr& lease, Lease::Type exp_type,
  147. uint8_t exp_pd_len = 128) {
  148. // that is belongs to the right subnet
  149. EXPECT_EQ(lease->subnet_id_, subnet_->getID());
  150. EXPECT_TRUE(subnet_->inRange(lease->addr_));
  151. EXPECT_TRUE(subnet_->inPool(exp_type, lease->addr_));
  152. // that it have proper parameters
  153. EXPECT_EQ(exp_type, lease->type_);
  154. EXPECT_EQ(iaid_, lease->iaid_);
  155. EXPECT_EQ(subnet_->getValid(), lease->valid_lft_);
  156. EXPECT_EQ(subnet_->getPreferred(), lease->preferred_lft_);
  157. EXPECT_EQ(subnet_->getT1(), lease->t1_);
  158. EXPECT_EQ(subnet_->getT2(), lease->t2_);
  159. EXPECT_EQ(exp_pd_len, lease->prefixlen_);
  160. EXPECT_EQ(fqdn_fwd_, lease->fqdn_fwd_);
  161. EXPECT_EQ(fqdn_rev_, lease->fqdn_rev_);
  162. EXPECT_EQ(hostname_, lease->hostname_);
  163. EXPECT_TRUE(*lease->duid_ == *duid_);
  164. /// @todo: check cltt
  165. }
  166. /// @brief Checks if specified address is increased properly
  167. ///
  168. /// Method uses gtest macros to mark check failure.
  169. ///
  170. /// @param alloc IterativeAllocator that is tested
  171. /// @param input address to be increased
  172. /// @param exp_output expected address after increase
  173. void
  174. checkAddrIncrease(NakedAllocEngine::NakedIterativeAllocator& alloc,
  175. std::string input, std::string exp_output) {
  176. EXPECT_EQ(exp_output, alloc.increaseAddress(IOAddress(input)).toText());
  177. }
  178. /// @brief Checks if increasePrefix() works as expected
  179. ///
  180. /// Method uses gtest macros to mark check failure.
  181. ///
  182. /// @param alloc allocator to be tested
  183. /// @param input IPv6 prefix (as a string)
  184. /// @param prefix_len prefix len
  185. /// @param exp_output expected output (string)
  186. void
  187. checkPrefixIncrease(NakedAllocEngine::NakedIterativeAllocator& alloc,
  188. std::string input, uint8_t prefix_len,
  189. std::string exp_output) {
  190. EXPECT_EQ(exp_output, alloc.increasePrefix(IOAddress(input), prefix_len)
  191. .toText());
  192. }
  193. /// @brief Checks if the simple allocation can succeed
  194. ///
  195. /// The type of lease is determined by pool type (pool->getType()
  196. ///
  197. /// @param pool pool from which the lease will be allocated from
  198. /// @param hint address to be used as a hint
  199. /// @param fake true - this is fake allocation (SOLICIT)
  200. /// @return allocated lease (or NULL)
  201. Lease6Ptr simpleAlloc6Test(const Pool6Ptr& pool, const IOAddress& hint,
  202. bool fake) {
  203. Lease::Type type = pool->getType();
  204. uint8_t expected_len = pool->getLength();
  205. boost::scoped_ptr<AllocEngine> engine;
  206. EXPECT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  207. 100)));
  208. // We can't use ASSERT macros in non-void methods
  209. EXPECT_TRUE(engine);
  210. if (!engine) {
  211. return (Lease6Ptr());
  212. }
  213. Lease6Ptr lease;
  214. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  215. duid_, iaid_, hint, type, false, false,
  216. "", fake, CalloutHandlePtr(), old_leases_, HWAddrPtr())));
  217. // Check that we got a lease
  218. EXPECT_TRUE(lease);
  219. if (!lease) {
  220. return (Lease6Ptr());
  221. }
  222. // Do all checks on the lease
  223. checkLease6(lease, type, expected_len);
  224. // Check that the lease is indeed in LeaseMgr
  225. Lease6Ptr from_mgr = LeaseMgrFactory::instance().getLease6(type,
  226. lease->addr_);
  227. if (!fake) {
  228. // This is a real (REQUEST) allocation, the lease must be in the DB
  229. EXPECT_TRUE(from_mgr);
  230. if (!from_mgr) {
  231. return (Lease6Ptr());
  232. }
  233. // Now check that the lease in LeaseMgr has the same parameters
  234. detailCompareLease(lease, from_mgr);
  235. } else {
  236. // This is a fake (SOLICIT) allocation, the lease must not be in DB
  237. EXPECT_FALSE(from_mgr);
  238. if (from_mgr) {
  239. return (Lease6Ptr());
  240. }
  241. }
  242. return (lease);
  243. }
  244. /// @brief Checks if the address allocation with a hint that is in range,
  245. /// in pool, but is currently used, can succeed
  246. ///
  247. /// Method uses gtest macros to mark check failure.
  248. ///
  249. /// @param type lease type
  250. /// @param used_addr address should be preallocated (simulates prior
  251. /// allocation by some other user)
  252. /// @param requested address requested by the client
  253. /// @param expected_pd_len expected PD len (128 for addresses)
  254. void allocWithUsedHintTest(Lease::Type type, IOAddress used_addr,
  255. IOAddress requested, uint8_t expected_pd_len) {
  256. boost::scoped_ptr<AllocEngine> engine;
  257. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  258. 100)));
  259. ASSERT_TRUE(engine);
  260. // Let's create a lease and put it in the LeaseMgr
  261. DuidPtr duid2 = boost::shared_ptr<DUID>(new DUID(vector<uint8_t>(8, 0xff)));
  262. time_t now = time(NULL);
  263. Lease6Ptr used(new Lease6(type, used_addr,
  264. duid2, 1, 2, 3, 4, now, subnet_->getID()));
  265. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  266. // Another client comes in and request an address that is in pool, but
  267. // unfortunately it is used already. The same address must not be allocated
  268. // twice.
  269. Lease6Ptr lease;
  270. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  271. duid_, iaid_, requested, type, false, false, "", false,
  272. CalloutHandlePtr(), old_leases_, HWAddrPtr())));
  273. // Check that we got a lease
  274. ASSERT_TRUE(lease);
  275. // Allocated address must be different
  276. EXPECT_NE(used_addr, lease->addr_);
  277. // We should NOT get what we asked for, because it is used already
  278. EXPECT_NE(requested, lease->addr_);
  279. // Do all checks on the lease
  280. checkLease6(lease, type, expected_pd_len);
  281. // Check that the lease is indeed in LeaseMgr
  282. Lease6Ptr from_mgr = LeaseMgrFactory::instance().getLease6(lease->type_,
  283. lease->addr_);
  284. ASSERT_TRUE(from_mgr);
  285. // Now check that the lease in LeaseMgr has the same parameters
  286. detailCompareLease(lease, from_mgr);
  287. }
  288. /// @brief checks if bogus hint can be ignored and the allocation succeeds
  289. ///
  290. /// This test checks if the allocation with a hing that is out of the blue
  291. /// can succeed. The invalid hint should be ingored completely.
  292. ///
  293. /// @param type Lease type
  294. /// @param hint hint (as send by a client)
  295. /// @param expectd_pd_len (used in validation)
  296. void allocBogusHint6(Lease::Type type, IOAddress hint,
  297. uint8_t expected_pd_len) {
  298. boost::scoped_ptr<AllocEngine> engine;
  299. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  300. 100)));
  301. ASSERT_TRUE(engine);
  302. // Client would like to get a 3000::abc lease, which does not belong to any
  303. // supported lease. Allocation engine should ignore it and carry on
  304. // with the normal allocation
  305. Lease6Ptr lease;
  306. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  307. duid_, iaid_, hint, type, false,
  308. false, "", false, CalloutHandlePtr(), old_leases_,
  309. HWAddrPtr())));
  310. // Check that we got a lease
  311. ASSERT_TRUE(lease);
  312. // We should NOT get what we asked for, because it is used already
  313. EXPECT_NE(hint, lease->addr_);
  314. // Do all checks on the lease
  315. checkLease6(lease, type, expected_pd_len);
  316. // Check that the lease is indeed in LeaseMgr
  317. Lease6Ptr from_mgr = LeaseMgrFactory::instance().getLease6(lease->type_,
  318. lease->addr_);
  319. ASSERT_TRUE(from_mgr);
  320. // Now check that the lease in LeaseMgr has the same parameters
  321. detailCompareLease(lease, from_mgr);
  322. }
  323. virtual ~AllocEngine6Test() {
  324. factory_.destroy();
  325. }
  326. DuidPtr duid_; ///< client-identifier (value used in tests)
  327. uint32_t iaid_; ///< IA identifier (value used in tests)
  328. Subnet6Ptr subnet_; ///< subnet6 (used in tests)
  329. Pool6Ptr pool_; ///< NA pool belonging to subnet_
  330. Pool6Ptr pd_pool_; ///< PD pool belonging to subnet_
  331. std::string hostname_; ///< Hostname
  332. bool fqdn_fwd_; ///< Perform forward update for a lease.
  333. bool fqdn_rev_; ///< Perform reverse update for a lease.
  334. LeaseMgrFactory factory_; ///< pointer to LeaseMgr factory
  335. /// @brief Collection of leases being replaced by newly allocated or renewed
  336. /// leases.
  337. Lease6Collection old_leases_;
  338. };
  339. /// @brief Used in Allocation Engine tests for IPv4
  340. class AllocEngine4Test : public ::testing::Test {
  341. public:
  342. /// @brief Default constructor
  343. ///
  344. /// Sets clientid_, hwaddr_, subnet_, pool_ fields to example values
  345. /// used in many tests, initializes cfg_mgr configuration and creates
  346. /// lease database.
  347. ///
  348. /// It also re-initializes the Host Manager.
  349. AllocEngine4Test() {
  350. // Create fresh instance of the HostMgr, and drop any previous HostMgr
  351. // state.
  352. HostMgr::instance().create();
  353. clientid_ = ClientIdPtr(new ClientId(vector<uint8_t>(8, 0x44)));
  354. uint8_t mac[] = { 0, 1, 22, 33, 44, 55};
  355. // Let's use odd hardware type to check if there is no Ethernet
  356. // hardcoded anywhere.
  357. hwaddr_ = HWAddrPtr(new HWAddr(mac, sizeof(mac), HTYPE_FDDI));
  358. // Allocate different MAC address for the tests that require two
  359. // different MAC addresses.
  360. ++mac[sizeof(mac) - 1];
  361. hwaddr2_ = HWAddrPtr(new HWAddr(mac, sizeof (mac), HTYPE_FDDI));
  362. // instantiate cfg_mgr
  363. CfgMgr& cfg_mgr = CfgMgr::instance();
  364. subnet_ = Subnet4Ptr(new Subnet4(IOAddress("192.0.2.0"), 24, 1, 2, 3));
  365. pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"),
  366. IOAddress("192.0.2.109")));
  367. subnet_->addPool(pool_);
  368. cfg_mgr.getStagingCfg()->getCfgSubnets4()->add(subnet_);
  369. cfg_mgr.commit();
  370. factory_.create("type=memfile universe=4 persist=false");
  371. // Create a default context. Note that remaining parameters must be
  372. // assigned when needed.
  373. ctx_.subnet_ = subnet_;
  374. ctx_.clientid_ = clientid_;
  375. ctx_.hwaddr_ = hwaddr_;
  376. ctx_.callout_handle_ = HooksManager::createCalloutHandle();
  377. }
  378. /// @brief checks if Lease4 matches expected configuration
  379. ///
  380. /// @param lease lease to be checked
  381. void checkLease4(const Lease4Ptr& lease) {
  382. // Check that is belongs to the right subnet
  383. EXPECT_EQ(lease->subnet_id_, subnet_->getID());
  384. EXPECT_TRUE(subnet_->inRange(lease->addr_));
  385. EXPECT_TRUE(subnet_->inPool(Lease::TYPE_V4, lease->addr_));
  386. // Check that it has proper parameters
  387. EXPECT_EQ(subnet_->getValid(), lease->valid_lft_);
  388. EXPECT_EQ(subnet_->getT1(), lease->t1_);
  389. EXPECT_EQ(subnet_->getT2(), lease->t2_);
  390. if (lease->client_id_ && !clientid_) {
  391. ADD_FAILURE() << "Lease4 has a client-id, while it should have none.";
  392. } else
  393. if (!lease->client_id_ && clientid_) {
  394. ADD_FAILURE() << "Lease4 has no client-id, but it was expected to have one.";
  395. } else
  396. if (lease->client_id_ && clientid_) {
  397. EXPECT_TRUE(*lease->client_id_ == *clientid_);
  398. }
  399. EXPECT_TRUE(*lease->hwaddr_ == *hwaddr_);
  400. /// @todo: check cltt
  401. }
  402. virtual ~AllocEngine4Test() {
  403. factory_.destroy();
  404. }
  405. ClientIdPtr clientid_; ///< Client-identifier (value used in tests)
  406. HWAddrPtr hwaddr_; ///< Hardware address (value used in tests)
  407. HWAddrPtr hwaddr2_; ///< Alternative hardware address.
  408. Subnet4Ptr subnet_; ///< Subnet4 (used in tests)
  409. Pool4Ptr pool_; ///< Pool belonging to subnet_
  410. LeaseMgrFactory factory_; ///< Pointer to LeaseMgr factory
  411. Lease4Ptr old_lease_; ///< Holds previous instance of the lease.
  412. AllocEngine::ClientContext4 ctx_; ///< Context information passed to various
  413. ///< allocation engine functions.
  414. };
  415. // This test checks if the v6 Allocation Engine can be instantiated, parses
  416. // parameters string and allocators are created.
  417. TEST_F(AllocEngine6Test, constructor) {
  418. boost::scoped_ptr<AllocEngine> x;
  419. // Hashed and random allocators are not supported yet
  420. ASSERT_THROW(x.reset(new AllocEngine(AllocEngine::ALLOC_HASHED, 5)), NotImplemented);
  421. ASSERT_THROW(x.reset(new AllocEngine(AllocEngine::ALLOC_RANDOM, 5)), NotImplemented);
  422. ASSERT_NO_THROW(x.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100, true)));
  423. // Check that allocator for normal addresses is created
  424. ASSERT_TRUE(x->getAllocator(Lease::TYPE_NA));
  425. // Check that allocator for temporary address is created
  426. ASSERT_TRUE(x->getAllocator(Lease::TYPE_TA));
  427. // Check that allocator for prefixes is created
  428. ASSERT_TRUE(x->getAllocator(Lease::TYPE_PD));
  429. // There should be no V4 allocator
  430. EXPECT_THROW(x->getAllocator(Lease::TYPE_V4), BadValue);
  431. }
  432. // This test checks if the simple allocation (REQUEST) can succeed
  433. TEST_F(AllocEngine6Test, simpleAlloc6) {
  434. simpleAlloc6Test(pool_, IOAddress("::"), false);
  435. }
  436. // This test checks if the simple PD allocation (REQUEST) can succeed
  437. TEST_F(AllocEngine6Test, pdSimpleAlloc6) {
  438. simpleAlloc6Test(pd_pool_, IOAddress("::"), false);
  439. }
  440. // This test checks if the fake allocation (for SOLICIT) can succeed
  441. TEST_F(AllocEngine6Test, fakeAlloc6) {
  442. simpleAlloc6Test(pool_, IOAddress("::"), true);
  443. }
  444. // This test checks if the fake PD allocation (for SOLICIT) can succeed
  445. TEST_F(AllocEngine6Test, pdFakeAlloc6) {
  446. simpleAlloc6Test(pd_pool_, IOAddress("::"), true);
  447. };
  448. // This test checks if the allocation with a hint that is valid (in range,
  449. // in pool and free) can succeed
  450. TEST_F(AllocEngine6Test, allocWithValidHint6) {
  451. Lease6Ptr lease = simpleAlloc6Test(pool_, IOAddress("2001:db8:1::15"),
  452. false);
  453. // We should get what we asked for
  454. EXPECT_EQ("2001:db8:1::15", lease->addr_.toText());
  455. }
  456. // This test checks if the address allocation with a hint that is in range,
  457. // in pool, but is currently used, can succeed
  458. TEST_F(AllocEngine6Test, allocWithUsedHint6) {
  459. allocWithUsedHintTest(Lease::TYPE_NA,
  460. IOAddress("2001:db8:1::1f"), // allocate this as used
  461. IOAddress("2001:db8:1::1f"), // request this addr
  462. 128);
  463. }
  464. // This test checks if the PD allocation with a hint that is in range,
  465. // in pool, but is currently used, can succeed
  466. TEST_F(AllocEngine6Test, pdAllocWithUsedHint6) {
  467. allocWithUsedHintTest(Lease::TYPE_PD,
  468. IOAddress("2001:db8:1::"), // allocate this prefix as used
  469. IOAddress("2001:db8:1::"), // request this prefix
  470. 64);
  471. }
  472. // This test checks if the allocation with a hint that is out the blue
  473. // can succeed. The invalid hint should be ignored completely.
  474. TEST_F(AllocEngine6Test, allocBogusHint6) {
  475. allocBogusHint6(Lease::TYPE_NA, IOAddress("3000::abc"), 128);
  476. }
  477. // This test checks if the allocation with a hint that is out the blue
  478. // can succeed. The invalid hint should be ignored completely.
  479. TEST_F(AllocEngine6Test, pdAllocBogusHint6) {
  480. allocBogusHint6(Lease::TYPE_PD, IOAddress("3000::abc"), 64);
  481. }
  482. // This test checks that NULL values are handled properly
  483. TEST_F(AllocEngine6Test, allocateAddress6Nulls) {
  484. boost::scoped_ptr<AllocEngine> engine;
  485. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100)));
  486. ASSERT_TRUE(engine);
  487. // Allocations without subnet are not allowed
  488. Lease6Ptr lease;
  489. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(
  490. Subnet6Ptr(), duid_, iaid_, IOAddress("::"), Lease::TYPE_NA,
  491. false, false, "", false, CalloutHandlePtr(), old_leases_,
  492. HWAddrPtr())));
  493. ASSERT_FALSE(lease);
  494. // Allocations without DUID are not allowed either
  495. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  496. DuidPtr(), iaid_, IOAddress("::"), Lease::TYPE_NA, false,
  497. false, "", false, CalloutHandlePtr(), old_leases_,
  498. HWAddrPtr())));
  499. ASSERT_FALSE(lease);
  500. }
  501. // This test verifies that the allocator picks addresses that belong to the
  502. // pool
  503. TEST_F(AllocEngine6Test, IterativeAllocator) {
  504. boost::scoped_ptr<NakedAllocEngine::Allocator>
  505. alloc(new NakedAllocEngine::IterativeAllocator(Lease::TYPE_NA));
  506. for (int i = 0; i < 1000; ++i) {
  507. IOAddress candidate = alloc->pickAddress(subnet_, duid_, IOAddress("::"));
  508. EXPECT_TRUE(subnet_->inPool(Lease::TYPE_NA, candidate));
  509. }
  510. }
  511. TEST_F(AllocEngine6Test, IterativeAllocatorAddrStep) {
  512. NakedAllocEngine::NakedIterativeAllocator alloc(Lease::TYPE_NA);
  513. subnet_->delPools(Lease::TYPE_NA); // Get rid of default pool
  514. Pool6Ptr pool1(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1::1"),
  515. IOAddress("2001:db8:1::5")));
  516. Pool6Ptr pool2(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1::100"),
  517. IOAddress("2001:db8:1::100")));
  518. Pool6Ptr pool3(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1::105"),
  519. IOAddress("2001:db8:1::106")));
  520. subnet_->addPool(pool1);
  521. subnet_->addPool(pool2);
  522. subnet_->addPool(pool3);
  523. // Let's check the first pool (5 addresses here)
  524. EXPECT_EQ("2001:db8:1::1", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  525. EXPECT_EQ("2001:db8:1::2", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  526. EXPECT_EQ("2001:db8:1::3", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  527. EXPECT_EQ("2001:db8:1::4", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  528. EXPECT_EQ("2001:db8:1::5", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  529. // The second pool is easy - only one address here
  530. EXPECT_EQ("2001:db8:1::100", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  531. // This is the third and last pool, with 2 addresses in it
  532. EXPECT_EQ("2001:db8:1::105", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  533. EXPECT_EQ("2001:db8:1::106", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  534. // We iterated over all addresses and reached to the end of the last pool.
  535. // Let's wrap around and start from the beginning
  536. EXPECT_EQ("2001:db8:1::1", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  537. EXPECT_EQ("2001:db8:1::2", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  538. }
  539. TEST_F(AllocEngine6Test, IterativeAllocatorPrefixStep) {
  540. NakedAllocEngine::NakedIterativeAllocator alloc(Lease::TYPE_PD);
  541. subnet_.reset(new Subnet6(IOAddress("2001:db8::"), 32, 1, 2, 3, 4));
  542. Pool6Ptr pool1(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8::"), 56, 60));
  543. Pool6Ptr pool2(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:1::"), 48, 48));
  544. Pool6Ptr pool3(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:2::"), 56, 64));
  545. subnet_->addPool(pool1);
  546. subnet_->addPool(pool2);
  547. subnet_->addPool(pool3);
  548. // We have a 2001:db8::/48 subnet that has 3 pools defined in it:
  549. // 2001:db8::/56 split into /60 prefixes (16 leases) (or 2001:db8:0:X0::)
  550. // 2001:db8:1::/48 split into a single /48 prefix (just 1 lease)
  551. // 2001:db8:2::/56 split into /64 prefixes (256 leases) (or 2001:db8:2:XX::)
  552. // First pool check (Let's check over all 16 leases)
  553. EXPECT_EQ("2001:db8::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  554. EXPECT_EQ("2001:db8:0:10::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  555. EXPECT_EQ("2001:db8:0:20::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  556. EXPECT_EQ("2001:db8:0:30::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  557. EXPECT_EQ("2001:db8:0:40::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  558. EXPECT_EQ("2001:db8:0:50::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  559. EXPECT_EQ("2001:db8:0:60::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  560. EXPECT_EQ("2001:db8:0:70::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  561. EXPECT_EQ("2001:db8:0:80::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  562. EXPECT_EQ("2001:db8:0:90::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  563. EXPECT_EQ("2001:db8:0:a0::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  564. EXPECT_EQ("2001:db8:0:b0::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  565. EXPECT_EQ("2001:db8:0:c0::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  566. EXPECT_EQ("2001:db8:0:d0::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  567. EXPECT_EQ("2001:db8:0:e0::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  568. EXPECT_EQ("2001:db8:0:f0::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  569. // Second pool (just one lease here)
  570. EXPECT_EQ("2001:db8:1::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  571. // Third pool (256 leases, let's check first and last explictly and the
  572. // rest over in a pool
  573. EXPECT_EQ("2001:db8:2::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  574. for (int i = 1; i < 255; i++) {
  575. stringstream exp;
  576. exp << "2001:db8:2:" << hex << i << dec << "::";
  577. EXPECT_EQ(exp.str(), alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  578. }
  579. EXPECT_EQ("2001:db8:2:ff::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  580. // Ok, we've iterated over all prefixes in all pools. We now wrap around.
  581. // We're looping over now (iterating over first pool again)
  582. EXPECT_EQ("2001:db8::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  583. EXPECT_EQ("2001:db8:0:10::", alloc.pickAddress(subnet_, duid_, IOAddress("::")).toText());
  584. }
  585. // This test verifies that the iterative allocator can step over addresses
  586. TEST_F(AllocEngine6Test, IterativeAllocatorAddressIncrease) {
  587. NakedAllocEngine::NakedIterativeAllocator alloc(Lease::TYPE_NA);
  588. // Let's pick the first address
  589. IOAddress addr1 = alloc.pickAddress(subnet_, duid_, IOAddress("2001:db8:1::10"));
  590. // Check that we can indeed pick the first address from the pool
  591. EXPECT_EQ("2001:db8:1::10", addr1.toText());
  592. // Check that addresses can be increased properly
  593. checkAddrIncrease(alloc, "2001:db8::9", "2001:db8::a");
  594. checkAddrIncrease(alloc, "2001:db8::f", "2001:db8::10");
  595. checkAddrIncrease(alloc, "2001:db8::10", "2001:db8::11");
  596. checkAddrIncrease(alloc, "2001:db8::ff", "2001:db8::100");
  597. checkAddrIncrease(alloc, "2001:db8::ffff", "2001:db8::1:0");
  598. checkAddrIncrease(alloc, "::", "::1");
  599. checkAddrIncrease(alloc, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "::");
  600. }
  601. // This test verifies that the allocator can step over prefixes
  602. TEST_F(AllocEngine6Test, IterativeAllocatorPrefixIncrease) {
  603. NakedAllocEngine::NakedIterativeAllocator alloc(Lease::TYPE_PD);
  604. // For /128 prefix, increasePrefix should work the same as addressIncrease
  605. checkPrefixIncrease(alloc, "2001:db8::9", 128, "2001:db8::a");
  606. checkPrefixIncrease(alloc, "2001:db8::f", 128, "2001:db8::10");
  607. checkPrefixIncrease(alloc, "2001:db8::10", 128, "2001:db8::11");
  608. checkPrefixIncrease(alloc, "2001:db8::ff", 128, "2001:db8::100");
  609. checkPrefixIncrease(alloc, "2001:db8::ffff", 128, "2001:db8::1:0");
  610. checkPrefixIncrease(alloc, "::", 128, "::1");
  611. checkPrefixIncrease(alloc, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 128, "::");
  612. // Check that /64 prefixes can be generated
  613. checkPrefixIncrease(alloc, "2001:db8::", 64, "2001:db8:0:1::");
  614. // Check that prefix length not divisible by 8 are working
  615. checkPrefixIncrease(alloc, "2001:db8::", 128, "2001:db8::1");
  616. checkPrefixIncrease(alloc, "2001:db8::", 127, "2001:db8::2");
  617. checkPrefixIncrease(alloc, "2001:db8::", 126, "2001:db8::4");
  618. checkPrefixIncrease(alloc, "2001:db8::", 125, "2001:db8::8");
  619. checkPrefixIncrease(alloc, "2001:db8::", 124, "2001:db8::10");
  620. checkPrefixIncrease(alloc, "2001:db8::", 123, "2001:db8::20");
  621. checkPrefixIncrease(alloc, "2001:db8::", 122, "2001:db8::40");
  622. checkPrefixIncrease(alloc, "2001:db8::", 121, "2001:db8::80");
  623. checkPrefixIncrease(alloc, "2001:db8::", 120, "2001:db8::100");
  624. // These are not really useful cases, because there are bits set
  625. // int the last (128 - prefix_len) bits. Nevertheless, it shows
  626. // that the algorithm is working even in such cases
  627. checkPrefixIncrease(alloc, "2001:db8::1", 128, "2001:db8::2");
  628. checkPrefixIncrease(alloc, "2001:db8::1", 127, "2001:db8::3");
  629. checkPrefixIncrease(alloc, "2001:db8::1", 126, "2001:db8::5");
  630. checkPrefixIncrease(alloc, "2001:db8::1", 125, "2001:db8::9");
  631. checkPrefixIncrease(alloc, "2001:db8::1", 124, "2001:db8::11");
  632. checkPrefixIncrease(alloc, "2001:db8::1", 123, "2001:db8::21");
  633. checkPrefixIncrease(alloc, "2001:db8::1", 122, "2001:db8::41");
  634. checkPrefixIncrease(alloc, "2001:db8::1", 121, "2001:db8::81");
  635. checkPrefixIncrease(alloc, "2001:db8::1", 120, "2001:db8::101");
  636. // Let's try out couple real life scenarios
  637. checkPrefixIncrease(alloc, "2001:db8:1:abcd::", 64, "2001:db8:1:abce::");
  638. checkPrefixIncrease(alloc, "2001:db8:1:abcd::", 60, "2001:db8:1:abdd::");
  639. checkPrefixIncrease(alloc, "2001:db8:1:abcd::", 56, "2001:db8:1:accd::");
  640. checkPrefixIncrease(alloc, "2001:db8:1:abcd::", 52, "2001:db8:1:bbcd::");
  641. // And now let's try something over the top
  642. checkPrefixIncrease(alloc, "::", 1, "8000::");
  643. }
  644. // This test verifies that the iterative allocator really walks over all addresses
  645. // in all pools in specified subnet. It also must not pick the same address twice
  646. // unless it runs out of pool space and must start over.
  647. TEST_F(AllocEngine6Test, IterativeAllocator_manyPools6) {
  648. NakedAllocEngine::IterativeAllocator alloc(Lease::TYPE_NA);
  649. // let's start from 2, as there is 2001:db8:1::10 - 2001:db8:1::20 pool already.
  650. for (int i = 2; i < 10; ++i) {
  651. stringstream min, max;
  652. min << "2001:db8:1::" << hex << i*16 + 1;
  653. max << "2001:db8:1::" << hex << i*16 + 9;
  654. Pool6Ptr pool(new Pool6(Lease::TYPE_NA, IOAddress(min.str()),
  655. IOAddress(max.str())));
  656. subnet_->addPool(pool);
  657. }
  658. int total = 17 + 8 * 9; // First pool (::10 - ::20) has 17 addresses in it,
  659. // there are 8 extra pools with 9 addresses in each.
  660. // Let's keep picked addresses here and check their uniqueness.
  661. std::set<IOAddress> generated_addrs;
  662. int cnt = 0;
  663. while (++cnt) {
  664. IOAddress candidate = alloc.pickAddress(subnet_, duid_, IOAddress("::"));
  665. EXPECT_TRUE(subnet_->inPool(Lease::TYPE_NA, candidate));
  666. // One way to easily verify that the iterative allocator really works is
  667. // to uncomment the following line and observe its output that it
  668. // covers all defined pools.
  669. // cout << candidate.toText() << endl;
  670. if (generated_addrs.find(candidate) == generated_addrs.end()) {
  671. // We haven't had this.
  672. generated_addrs.insert(candidate);
  673. } else {
  674. // We have seen this address before. That should mean that we
  675. // iterated over all addresses.
  676. if (generated_addrs.size() == total) {
  677. // We have exactly the number of address in all pools.
  678. break;
  679. }
  680. ADD_FAILURE() << "Too many or not enough unique addresses generated.";
  681. break;
  682. }
  683. if ( cnt>total ) {
  684. ADD_FAILURE() << "Too many unique addresses generated.";
  685. break;
  686. }
  687. }
  688. }
  689. // This test checks if really small pools are working
  690. TEST_F(AllocEngine6Test, smallPool6) {
  691. boost::scoped_ptr<AllocEngine> engine;
  692. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100)));
  693. ASSERT_TRUE(engine);
  694. IOAddress addr("2001:db8:1::ad");
  695. // Create a subnet with a pool that has one address.
  696. initSubnet(IOAddress("2001:db8:1::"), addr, addr);
  697. // Initialize FQDN for a lease.
  698. initFqdn("myhost.example.com", true, true);
  699. Lease6Ptr lease;
  700. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  701. duid_, iaid_, IOAddress("::"), Lease::TYPE_NA, fqdn_fwd_,
  702. fqdn_rev_, hostname_, false, CalloutHandlePtr(),
  703. old_leases_, HWAddrPtr())));
  704. // Check that we got that single lease
  705. ASSERT_TRUE(lease);
  706. EXPECT_EQ("2001:db8:1::ad", lease->addr_.toText());
  707. // Do all checks on the lease
  708. checkLease6(lease, Lease::TYPE_NA, 128);
  709. // Check that the lease is indeed in LeaseMgr
  710. Lease6Ptr from_mgr = LeaseMgrFactory::instance().getLease6(lease->type_,
  711. lease->addr_);
  712. ASSERT_TRUE(from_mgr);
  713. // Now check that the lease in LeaseMgr has the same parameters
  714. detailCompareLease(lease, from_mgr);
  715. // This is a new lease allocation. The old lease corresponding to a newly
  716. // allocated lease should be NULL.
  717. ASSERT_EQ(1, old_leases_.size());
  718. EXPECT_FALSE(old_leases_[0]);
  719. }
  720. // This test checks if all addresses in a pool are currently used, the attempt
  721. // to find out a new lease fails.
  722. TEST_F(AllocEngine6Test, outOfAddresses6) {
  723. boost::scoped_ptr<AllocEngine> engine;
  724. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100)));
  725. ASSERT_TRUE(engine);
  726. IOAddress addr("2001:db8:1::ad");
  727. CfgMgr& cfg_mgr = CfgMgr::instance();
  728. cfg_mgr.clear(); // Get rid of the default test configuration
  729. // Create configuration similar to other tests, but with a single address pool
  730. subnet_ = Subnet6Ptr(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
  731. pool_ = Pool6Ptr(new Pool6(Lease::TYPE_NA, addr, addr)); // just a single address
  732. subnet_->addPool(pool_);
  733. cfg_mgr.getStagingCfg()->getCfgSubnets6()->add(subnet_);
  734. // Just a different duid
  735. DuidPtr other_duid = DuidPtr(new DUID(vector<uint8_t>(12, 0xff)));
  736. const uint32_t other_iaid = 3568;
  737. Lease6Ptr lease(new Lease6(Lease::TYPE_NA, addr, other_duid, other_iaid,
  738. 501, 502, 503, 504, subnet_->getID(),
  739. HWAddrPtr(), 0));
  740. lease->cltt_ = time(NULL) - 10; // Allocated 10 seconds ago
  741. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(lease));
  742. // There is just a single address in the pool and allocated it to someone
  743. // else, so the allocation should fail
  744. Lease6Ptr lease2;
  745. EXPECT_NO_THROW(lease2 = expectOneLease(engine->allocateLeases6(subnet_,
  746. duid_, iaid_, IOAddress("::"), Lease::TYPE_NA, false, false,
  747. "", false, CalloutHandlePtr(), old_leases_, HWAddrPtr())));
  748. EXPECT_FALSE(lease2);
  749. }
  750. // This test checks if an expired lease can be reused in SOLICIT (fake allocation)
  751. TEST_F(AllocEngine6Test, solicitReuseExpiredLease6) {
  752. boost::scoped_ptr<AllocEngine> engine;
  753. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100)));
  754. ASSERT_TRUE(engine);
  755. IOAddress addr("2001:db8:1::ad");
  756. // Create one subnet with a pool holding one address.
  757. initSubnet(IOAddress("2001:db8:1::"), addr, addr);
  758. // Initialize FQDN data for the lease.
  759. initFqdn("myhost.example.com", true, true);
  760. // Just a different duid
  761. DuidPtr other_duid = DuidPtr(new DUID(vector<uint8_t>(12, 0xff)));
  762. const uint32_t other_iaid = 3568;
  763. Lease6Ptr lease(new Lease6(Lease::TYPE_NA, addr, other_duid, other_iaid,
  764. 501, 502, 503, 504, subnet_->getID(),
  765. HWAddrPtr(), 0));
  766. lease->cltt_ = time(NULL) - 500; // Allocated 500 seconds ago
  767. lease->valid_lft_ = 495; // Lease was valid for 495 seconds
  768. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(lease));
  769. // Make sure that we really created expired lease
  770. ASSERT_TRUE(lease->expired());
  771. // CASE 1: Asking for any address
  772. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  773. duid_, iaid_, IOAddress("::"), Lease::TYPE_NA, fqdn_fwd_,
  774. fqdn_rev_, hostname_, true, CalloutHandlePtr(),
  775. old_leases_, HWAddrPtr())));
  776. // Check that we got that single lease
  777. ASSERT_TRUE(lease);
  778. EXPECT_EQ(addr, lease->addr_);
  779. // Do all checks on the lease (if subnet-id, preferred/valid times are ok etc.)
  780. checkLease6(lease, Lease::TYPE_NA, 128);
  781. // CASE 2: Asking specifically for this address
  782. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  783. duid_, iaid_, addr, Lease::TYPE_NA, false, false, "",
  784. true, CalloutHandlePtr(), old_leases_, HWAddrPtr())));
  785. // Check that we got that single lease
  786. ASSERT_TRUE(lease);
  787. EXPECT_EQ(addr, lease->addr_);
  788. }
  789. // This test checks if an expired lease can be reused in REQUEST (actual allocation)
  790. TEST_F(AllocEngine6Test, requestReuseExpiredLease6) {
  791. boost::scoped_ptr<AllocEngine> engine;
  792. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100)));
  793. ASSERT_TRUE(engine);
  794. IOAddress addr("2001:db8:1::ad");
  795. CfgMgr& cfg_mgr = CfgMgr::instance();
  796. cfg_mgr.clear(); // Get rid of the default test configuration
  797. // Create configuration similar to other tests, but with a single address pool
  798. subnet_ = Subnet6Ptr(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
  799. pool_ = Pool6Ptr(new Pool6(Lease::TYPE_NA, addr, addr)); // just a single address
  800. subnet_->addPool(pool_);
  801. cfg_mgr.getStagingCfg()->getCfgSubnets6()->add(subnet_);
  802. cfg_mgr.commit();
  803. // Let's create an expired lease
  804. DuidPtr other_duid = DuidPtr(new DUID(vector<uint8_t>(12, 0xff)));
  805. const uint32_t other_iaid = 3568;
  806. const SubnetID other_subnetid = 999;
  807. Lease6Ptr lease(new Lease6(Lease::TYPE_NA, addr, other_duid, other_iaid,
  808. 501, 502, 503, 504, other_subnetid, HWAddrPtr(),
  809. 0));
  810. lease->cltt_ = time(NULL) - 500; // Allocated 500 seconds ago
  811. lease->valid_lft_ = 495; // Lease was valid for 495 seconds
  812. lease->fqdn_fwd_ = true;
  813. lease->fqdn_rev_ = true;
  814. lease->hostname_ = "myhost.example.com.";
  815. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(lease));
  816. // A client comes along, asking specifically for this address
  817. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  818. duid_, iaid_, addr, Lease::TYPE_NA, false, false, "",
  819. false, CalloutHandlePtr(), old_leases_, HWAddrPtr())));
  820. // Check that he got that single lease
  821. ASSERT_TRUE(lease);
  822. EXPECT_EQ(addr, lease->addr_);
  823. // This reactivated lease should have updated FQDN data.
  824. EXPECT_TRUE(lease->hostname_.empty());
  825. EXPECT_FALSE(lease->fqdn_fwd_);
  826. EXPECT_FALSE(lease->fqdn_rev_);
  827. // Check that the old lease has been returned.
  828. Lease6Ptr old_lease = expectOneLease(old_leases_);
  829. // It should at least have the same IPv6 address.
  830. EXPECT_EQ(lease->addr_, old_lease->addr_);
  831. // Check that it carries not updated FQDN data.
  832. EXPECT_EQ("myhost.example.com.", old_lease->hostname_);
  833. EXPECT_TRUE(old_lease->fqdn_fwd_);
  834. EXPECT_TRUE(old_lease->fqdn_rev_);
  835. // Check that the lease is indeed updated in LeaseMgr
  836. Lease6Ptr from_mgr = LeaseMgrFactory::instance().getLease6(Lease::TYPE_NA,
  837. addr);
  838. ASSERT_TRUE(from_mgr);
  839. // Now check that the lease in LeaseMgr has the same parameters
  840. detailCompareLease(lease, from_mgr);
  841. }
  842. // --- IPv4 ---
  843. // This test checks if the v4 Allocation Engine can be instantiated, parses
  844. // parameters string and allocators are created.
  845. TEST_F(AllocEngine4Test, constructor) {
  846. boost::scoped_ptr<AllocEngine> x;
  847. // Hashed and random allocators are not supported yet
  848. ASSERT_THROW(x.reset(new AllocEngine(AllocEngine::ALLOC_HASHED, 5, false)),
  849. NotImplemented);
  850. ASSERT_THROW(x.reset(new AllocEngine(AllocEngine::ALLOC_RANDOM, 5, false)),
  851. NotImplemented);
  852. // Create V4 (ipv6=false) Allocation Engine that will try at most
  853. // 100 attempts to pick up a lease
  854. ASSERT_NO_THROW(x.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100,
  855. false)));
  856. // There should be V4 allocator
  857. ASSERT_TRUE(x->getAllocator(Lease::TYPE_V4));
  858. // Check that allocators for V6 stuff are not created
  859. EXPECT_THROW(x->getAllocator(Lease::TYPE_NA), BadValue);
  860. EXPECT_THROW(x->getAllocator(Lease::TYPE_TA), BadValue);
  861. EXPECT_THROW(x->getAllocator(Lease::TYPE_PD), BadValue);
  862. }
  863. // This test checks if the simple IPv4 allocation can succeed
  864. TEST_F(AllocEngine4Test, simpleAlloc4) {
  865. boost::scoped_ptr<AllocEngine> engine;
  866. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  867. 100, false)));
  868. ASSERT_TRUE(engine);
  869. Lease4Ptr lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  870. IOAddress("0.0.0.0"),
  871. false, true,
  872. "somehost.example.com.",
  873. false, CalloutHandlePtr(),
  874. old_lease_);
  875. // The new lease has been allocated, so the old lease should not exist.
  876. EXPECT_FALSE(old_lease_);
  877. // Check that we got a lease
  878. ASSERT_TRUE(lease);
  879. // Do all checks on the lease
  880. checkLease4(lease);
  881. // Check that the lease is indeed in LeaseMgr
  882. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  883. ASSERT_TRUE(from_mgr);
  884. // Now check that the lease in LeaseMgr has the same parameters
  885. detailCompareLease(lease, from_mgr);
  886. }
  887. // This test checks if the fake allocation (for DISCOVER) can succeed
  888. TEST_F(AllocEngine4Test, fakeAlloc4) {
  889. boost::scoped_ptr<AllocEngine> engine;
  890. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  891. 100, false)));
  892. ASSERT_TRUE(engine);
  893. Lease4Ptr lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  894. IOAddress("0.0.0.0"),
  895. false, true, "host.example.com.",
  896. true, CalloutHandlePtr(),
  897. old_lease_);
  898. // The new lease has been allocated, so the old lease should not exist.
  899. EXPECT_FALSE(old_lease_);
  900. // Check that we got a lease
  901. ASSERT_TRUE(lease);
  902. // Do all checks on the lease
  903. checkLease4(lease);
  904. // Check that the lease is NOT in LeaseMgr
  905. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  906. ASSERT_FALSE(from_mgr);
  907. }
  908. // This test checks if the allocation with a hint that is valid (in range,
  909. // in pool and free) can succeed
  910. TEST_F(AllocEngine4Test, allocWithValidHint4) {
  911. boost::scoped_ptr<AllocEngine> engine;
  912. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  913. 100, false)));
  914. ASSERT_TRUE(engine);
  915. Lease4Ptr lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  916. IOAddress("192.0.2.105"),
  917. true, true, "host.example.com.",
  918. false, CalloutHandlePtr(),
  919. old_lease_);
  920. // Check that we got a lease
  921. ASSERT_TRUE(lease);
  922. // We have allocated the new lease, so the old lease should not exist.
  923. EXPECT_FALSE(old_lease_);
  924. // We should get what we asked for
  925. EXPECT_EQ(lease->addr_.toText(), "192.0.2.105");
  926. // Do all checks on the lease
  927. checkLease4(lease);
  928. // Check that the lease is indeed in LeaseMgr
  929. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  930. ASSERT_TRUE(from_mgr);
  931. // Now check that the lease in LeaseMgr has the same parameters
  932. detailCompareLease(lease, from_mgr);
  933. }
  934. // This test checks if the allocation with a hint that is in range,
  935. // in pool, but is currently used) can succeed
  936. TEST_F(AllocEngine4Test, allocWithUsedHint4) {
  937. boost::scoped_ptr<AllocEngine> engine;
  938. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  939. 100, false)));
  940. ASSERT_TRUE(engine);
  941. // Let's create a lease and put it in the LeaseMgr
  942. uint8_t hwaddr2_data[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  943. HWAddrPtr hwaddr2(new HWAddr(hwaddr2_data, sizeof(hwaddr2_data), HTYPE_ETHER));
  944. uint8_t clientid2[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
  945. time_t now = time(NULL);
  946. Lease4Ptr used(new Lease4(IOAddress("192.0.2.106"), hwaddr2,
  947. clientid2, sizeof(clientid2), 1, 2, 3, now, subnet_->getID()));
  948. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  949. // Another client comes in and request an address that is in pool, but
  950. // unfortunately it is used already. The same address must not be allocated
  951. // twice.
  952. Lease4Ptr lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  953. IOAddress("192.0.2.106"),
  954. false, false, "",
  955. false, CalloutHandlePtr(),
  956. old_lease_);
  957. // New lease has been allocated, so the old lease should not exist.
  958. EXPECT_FALSE(old_lease_);
  959. // Check that we got a lease
  960. ASSERT_TRUE(lease);
  961. // Allocated address must be different
  962. EXPECT_NE(used->addr_, lease->addr_);
  963. // We should NOT get what we asked for, because it is used already
  964. EXPECT_NE("192.0.2.106", lease->addr_.toText());
  965. // Do all checks on the lease
  966. checkLease4(lease);
  967. // Check that the lease is indeed in LeaseMgr
  968. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  969. ASSERT_TRUE(from_mgr);
  970. // Now check that the lease in LeaseMgr has the same parameters
  971. detailCompareLease(lease, from_mgr);
  972. }
  973. // This test checks if the allocation with a hint that is out the blue
  974. // can succeed. The invalid hint should be ignored completely.
  975. TEST_F(AllocEngine4Test, allocBogusHint4) {
  976. boost::scoped_ptr<AllocEngine> engine;
  977. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  978. 100, false)));
  979. ASSERT_TRUE(engine);
  980. // Client would like to get a 3000::abc lease, which does not belong to any
  981. // supported lease. Allocation engine should ignore it and carry on
  982. // with the normal allocation
  983. Lease4Ptr lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  984. IOAddress("10.1.1.1"),
  985. false, false, "",
  986. false, CalloutHandlePtr(),
  987. old_lease_);
  988. // Check that we got a lease
  989. ASSERT_TRUE(lease);
  990. // We have allocated a new lease, so the old lease should not exist.
  991. EXPECT_FALSE(old_lease_);
  992. // We should NOT get what we asked for, because it is used already
  993. EXPECT_NE("10.1.1.1", lease->addr_.toText());
  994. // Do all checks on the lease
  995. checkLease4(lease);
  996. // Check that the lease is indeed in LeaseMgr
  997. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  998. ASSERT_TRUE(from_mgr);
  999. // Now check that the lease in LeaseMgr has the same parameters
  1000. detailCompareLease(lease, from_mgr);
  1001. }
  1002. // This test checks that NULL values are handled properly
  1003. TEST_F(AllocEngine4Test, allocateLease4Nulls) {
  1004. boost::scoped_ptr<AllocEngine> engine;
  1005. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  1006. 100, false)));
  1007. ASSERT_TRUE(engine);
  1008. // Allocations without subnet are not allowed
  1009. Lease4Ptr lease = engine->allocateLease4(SubnetPtr(), clientid_, hwaddr_,
  1010. IOAddress("0.0.0.0"),
  1011. false, false, "",
  1012. false, CalloutHandlePtr(),
  1013. old_lease_);
  1014. EXPECT_FALSE(lease);
  1015. // Allocations without HW address are not allowed
  1016. lease = engine->allocateLease4(subnet_, clientid_, HWAddrPtr(),
  1017. IOAddress("0.0.0.0"),
  1018. false, false, "",
  1019. false, CalloutHandlePtr(),
  1020. old_lease_);
  1021. EXPECT_FALSE(lease);
  1022. EXPECT_FALSE(old_lease_);
  1023. // Allocations without client-id are allowed
  1024. clientid_ = ClientIdPtr();
  1025. lease = engine->allocateLease4(subnet_, ClientIdPtr(), hwaddr_,
  1026. IOAddress("0.0.0.0"),
  1027. true, true, "myhost.example.com.",
  1028. false, CalloutHandlePtr(),
  1029. old_lease_);
  1030. // Check that we got a lease
  1031. ASSERT_TRUE(lease);
  1032. // New lease has been allocated, so the old lease should not exist.
  1033. EXPECT_FALSE(old_lease_);
  1034. // Do all checks on the lease
  1035. checkLease4(lease);
  1036. // Check that the lease is indeed in LeaseMgr
  1037. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  1038. ASSERT_TRUE(from_mgr);
  1039. // Now check that the lease in LeaseMgr has the same parameters
  1040. detailCompareLease(lease, from_mgr);
  1041. }
  1042. // This test verifies that the allocator picks addresses that belong to the
  1043. // pool
  1044. TEST_F(AllocEngine4Test, IterativeAllocator) {
  1045. boost::scoped_ptr<NakedAllocEngine::Allocator>
  1046. alloc(new NakedAllocEngine::IterativeAllocator(Lease::TYPE_V4));
  1047. for (int i = 0; i < 1000; ++i) {
  1048. IOAddress candidate = alloc->pickAddress(subnet_, clientid_,
  1049. IOAddress("0.0.0.0"));
  1050. EXPECT_TRUE(subnet_->inPool(Lease::TYPE_V4, candidate));
  1051. }
  1052. }
  1053. // This test verifies that the iterative allocator really walks over all addresses
  1054. // in all pools in specified subnet. It also must not pick the same address twice
  1055. // unless it runs out of pool space and must start over.
  1056. TEST_F(AllocEngine4Test, IterativeAllocator_manyPools4) {
  1057. NakedAllocEngine::IterativeAllocator alloc(Lease::TYPE_V4);
  1058. // Let's start from 2, as there is 2001:db8:1::10 - 2001:db8:1::20 pool already.
  1059. for (int i = 2; i < 10; ++i) {
  1060. stringstream min, max;
  1061. min << "192.0.2." << i * 10 + 1;
  1062. max << "192.0.2." << i * 10 + 9;
  1063. Pool4Ptr pool(new Pool4(IOAddress(min.str()),
  1064. IOAddress(max.str())));
  1065. // cout << "Adding pool: " << min.str() << "-" << max.str() << endl;
  1066. subnet_->addPool(pool);
  1067. }
  1068. int total = 10 + 8 * 9; // first pool (.100 - .109) has 10 addresses in it,
  1069. // there are 8 extra pools with 9 addresses in each.
  1070. // Let's keep picked addresses here and check their uniqueness.
  1071. std::set<IOAddress> generated_addrs;
  1072. int cnt = 0;
  1073. while (++cnt) {
  1074. IOAddress candidate = alloc.pickAddress(subnet_, clientid_, IOAddress("0.0.0.0"));
  1075. EXPECT_TRUE(subnet_->inPool(Lease::TYPE_V4, candidate));
  1076. // One way to easily verify that the iterative allocator really works is
  1077. // to uncomment the following line and observe its output that it
  1078. // covers all defined subnets.
  1079. // cout << candidate.toText() << endl;
  1080. if (generated_addrs.find(candidate) == generated_addrs.end()) {
  1081. // We haven't had this
  1082. generated_addrs.insert(candidate);
  1083. } else {
  1084. // We have seen this address before. That should mean that we
  1085. // iterated over all addresses.
  1086. if (generated_addrs.size() == total) {
  1087. // We have exactly the number of address in all pools
  1088. break;
  1089. }
  1090. ADD_FAILURE() << "Too many or not enough unique addresses generated.";
  1091. break;
  1092. }
  1093. if ( cnt>total ) {
  1094. ADD_FAILURE() << "Too many unique addresses generated.";
  1095. break;
  1096. }
  1097. }
  1098. }
  1099. // This test checks if really small pools are working
  1100. TEST_F(AllocEngine4Test, smallPool4) {
  1101. boost::scoped_ptr<AllocEngine> engine;
  1102. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  1103. 100, false)));
  1104. ASSERT_TRUE(engine);
  1105. IOAddress addr("192.0.2.17");
  1106. CfgMgr& cfg_mgr = CfgMgr::instance();
  1107. // Get rid of the default subnet configuration.
  1108. cfg_mgr.clear();
  1109. // Create configuration similar to other tests, but with a single address pool
  1110. subnet_ = Subnet4Ptr(new Subnet4(IOAddress("192.0.2.0"), 24, 1, 2, 3));
  1111. pool_ = Pool4Ptr(new Pool4(addr, addr)); // just a single address
  1112. subnet_->addPool(pool_);
  1113. cfg_mgr.getStagingCfg()->getCfgSubnets4()->add(subnet_);
  1114. Lease4Ptr lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  1115. IOAddress("0.0.0.0"),
  1116. true, true, "host.example.com.",
  1117. false, CalloutHandlePtr(),
  1118. old_lease_);
  1119. // Check that we got that single lease
  1120. ASSERT_TRUE(lease);
  1121. // We have allocated new lease, so the old lease should not exist.
  1122. EXPECT_FALSE(old_lease_);
  1123. EXPECT_EQ("192.0.2.17", lease->addr_.toText());
  1124. // Do all checks on the lease
  1125. checkLease4(lease);
  1126. // Check that the lease is indeed in LeaseMgr
  1127. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  1128. ASSERT_TRUE(from_mgr);
  1129. // Now check that the lease in LeaseMgr has the same parameters
  1130. detailCompareLease(lease, from_mgr);
  1131. }
  1132. // This test checks if all addresses in a pool are currently used, the attempt
  1133. // to find out a new lease fails.
  1134. TEST_F(AllocEngine4Test, outOfAddresses4) {
  1135. boost::scoped_ptr<AllocEngine> engine;
  1136. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  1137. 100, false)));
  1138. ASSERT_TRUE(engine);
  1139. IOAddress addr("192.0.2.17");
  1140. CfgMgr& cfg_mgr = CfgMgr::instance();
  1141. // Get rid of the default test configuration.
  1142. cfg_mgr.clear();
  1143. // Create configuration similar to other tests, but with a single address pool
  1144. subnet_ = Subnet4Ptr(new Subnet4(IOAddress("192.0.2.0"), 24, 1, 2, 3));
  1145. pool_ = Pool4Ptr(new Pool4(addr, addr)); // just a single address
  1146. subnet_->addPool(pool_);
  1147. cfg_mgr.getStagingCfg()->getCfgSubnets4()->add(subnet_);
  1148. // Just a different hw/client-id for the second client
  1149. uint8_t hwaddr2_data[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  1150. HWAddrPtr hwaddr2(new HWAddr(hwaddr2_data, sizeof(hwaddr2_data), HTYPE_ETHER));
  1151. uint8_t clientid2[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
  1152. time_t now = time(NULL);
  1153. Lease4Ptr lease(new Lease4(addr, hwaddr2, clientid2,
  1154. sizeof(clientid2), 501, 502, 503, now,
  1155. subnet_->getID()));
  1156. lease->cltt_ = time(NULL) - 10; // Allocated 10 seconds ago
  1157. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(lease));
  1158. // There is just a single address in the pool and allocated it to someone
  1159. // else, so the allocation should fail
  1160. Lease4Ptr lease2 = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  1161. IOAddress("0.0.0.0"),
  1162. false, false, "",
  1163. false, CalloutHandlePtr(),
  1164. old_lease_);
  1165. EXPECT_FALSE(lease2);
  1166. EXPECT_FALSE(old_lease_);
  1167. }
  1168. // This test checks if an expired lease can be reused in DISCOVER (fake allocation)
  1169. TEST_F(AllocEngine4Test, discoverReuseExpiredLease4) {
  1170. boost::scoped_ptr<AllocEngine> engine;
  1171. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  1172. 100, false)));
  1173. ASSERT_TRUE(engine);
  1174. IOAddress addr("192.0.2.15");
  1175. CfgMgr& cfg_mgr = CfgMgr::instance();
  1176. // Get rid of the default test configuration.
  1177. cfg_mgr.clear();
  1178. // Create configuration similar to other tests, but with a single address pool
  1179. subnet_ = Subnet4Ptr(new Subnet4(IOAddress("192.0.2.0"), 24, 1, 2, 3));
  1180. pool_ = Pool4Ptr(new Pool4(addr, addr)); // just a single address
  1181. subnet_->addPool(pool_);
  1182. cfg_mgr.getStagingCfg()->getCfgSubnets4()->add(subnet_);
  1183. // Just a different hw/client-id for the second client
  1184. uint8_t hwaddr2_data[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  1185. HWAddrPtr hwaddr2(new HWAddr(hwaddr2_data, sizeof(hwaddr2_data), HTYPE_ETHER));
  1186. uint8_t clientid2[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
  1187. time_t now = time(NULL) - 500; // Allocated 500 seconds ago
  1188. Lease4Ptr lease(new Lease4(addr, hwaddr2, clientid2, sizeof(clientid2),
  1189. 495, 100, 200, now, subnet_->getID()));
  1190. // Copy the lease, so as it can be compared with the old lease returned
  1191. // by the allocation engine.
  1192. Lease4 original_lease(*lease);
  1193. // Lease was assigned 500 seconds ago, but its valid lifetime is 495, so it
  1194. // is expired already
  1195. ASSERT_TRUE(lease->expired());
  1196. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(lease));
  1197. // CASE 1: Asking for any address
  1198. lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  1199. IOAddress("0.0.0.0"),
  1200. false, false, "",
  1201. true, CalloutHandlePtr(),
  1202. old_lease_);
  1203. // Check that we got that single lease
  1204. ASSERT_TRUE(lease);
  1205. EXPECT_EQ(addr, lease->addr_);
  1206. // We are reusing expired lease, the old (expired) instance should be
  1207. // returned. The returned instance should be the same as the original
  1208. // lease.
  1209. ASSERT_TRUE(old_lease_);
  1210. EXPECT_TRUE(original_lease == *old_lease_);
  1211. // Do all checks on the lease (if subnet-id, preferred/valid times are ok etc.)
  1212. checkLease4(lease);
  1213. // CASE 2: Asking specifically for this address
  1214. lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  1215. IOAddress(addr),
  1216. false, false, "",
  1217. true, CalloutHandlePtr(),
  1218. old_lease_);
  1219. // Check that we got that single lease
  1220. ASSERT_TRUE(lease);
  1221. EXPECT_EQ(addr, lease->addr_);
  1222. // We are updating expired lease. The copy of the old lease should be
  1223. // returned and it should be equal to the original lease.
  1224. ASSERT_TRUE(old_lease_);
  1225. EXPECT_TRUE(*old_lease_ == original_lease);
  1226. }
  1227. // This test checks if an expired lease can be reused in REQUEST (actual allocation)
  1228. TEST_F(AllocEngine4Test, requestReuseExpiredLease4) {
  1229. boost::scoped_ptr<AllocEngine> engine;
  1230. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  1231. 100, false)));
  1232. ASSERT_TRUE(engine);
  1233. IOAddress addr("192.0.2.105");
  1234. // Just a different hw/client-id for the second client
  1235. uint8_t hwaddr2_data[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  1236. HWAddrPtr hwaddr2(new HWAddr(hwaddr2_data, sizeof(hwaddr2_data), HTYPE_ETHER));
  1237. uint8_t clientid2[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
  1238. time_t now = time(NULL) - 500; // Allocated 500 seconds ago
  1239. Lease4Ptr lease(new Lease4(addr, hwaddr2, clientid2, sizeof(clientid2),
  1240. sizeof(hwaddr2), 495, 100, 200, now,
  1241. subnet_->getID()));
  1242. // Make a copy of the lease, so as we can comapre that with the old lease
  1243. // instance returned by the allocation engine.
  1244. Lease4 original_lease(*lease);
  1245. // Lease was assigned 500 seconds ago, but its valid lifetime is 495, so it
  1246. // is expired already
  1247. ASSERT_TRUE(lease->expired());
  1248. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(lease));
  1249. // A client comes along, asking specifically for this address
  1250. lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  1251. IOAddress(addr),
  1252. false, true, "host.example.com.",
  1253. false, CalloutHandlePtr(),
  1254. old_lease_);
  1255. // Check that he got that single lease
  1256. ASSERT_TRUE(lease);
  1257. EXPECT_EQ(addr, lease->addr_);
  1258. // Check that the lease is indeed updated in LeaseMgr
  1259. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(addr);
  1260. ASSERT_TRUE(from_mgr);
  1261. // Now check that the lease in LeaseMgr has the same parameters
  1262. detailCompareLease(lease, from_mgr);
  1263. // The allocation engine should return a copy of the old lease. This
  1264. // lease should be equal to the original lease.
  1265. ASSERT_TRUE(old_lease_);
  1266. EXPECT_TRUE(*old_lease_ == original_lease);
  1267. }
  1268. /// @todo write renewLease6
  1269. // This test checks if a lease is really renewed when renewLease4 method is
  1270. // called
  1271. TEST_F(AllocEngine4Test, renewLease4) {
  1272. boost::scoped_ptr<AllocEngine> engine;
  1273. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  1274. 100, false)));
  1275. ASSERT_TRUE(engine);
  1276. IOAddress addr("192.0.2.102");
  1277. const uint32_t old_lifetime = 100;
  1278. const uint32_t old_t1 = 50;
  1279. const uint32_t old_t2 = 75;
  1280. const time_t old_timestamp = time(NULL) - 45; // Allocated 45 seconds ago
  1281. // Just a different hw/client-id for the second client
  1282. const uint8_t hwaddr2_data[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  1283. HWAddrPtr hwaddr2(new HWAddr(hwaddr2_data, sizeof(hwaddr2_data), HTYPE_ETHER));
  1284. const uint8_t clientid2[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
  1285. Lease4Ptr lease(new Lease4(addr, hwaddr2, clientid2, sizeof(clientid2),
  1286. old_lifetime, old_t1, old_t2,
  1287. old_timestamp, subnet_->getID()));
  1288. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(lease));
  1289. // Lease was assigned 45 seconds ago and is valid for 100 seconds. Let's
  1290. // renew it.
  1291. ASSERT_FALSE(lease->expired());
  1292. ctx_.fwd_dns_update_ = true;
  1293. ctx_.rev_dns_update_ = true;
  1294. ctx_.hostname_ = "host.example.com.";
  1295. ctx_.fake_allocation_ = false;
  1296. lease = engine->renewLease4(lease, ctx_);
  1297. // Check that he got that single lease
  1298. ASSERT_TRUE(lease);
  1299. EXPECT_EQ(addr, lease->addr_);
  1300. // Check that the lease matches subnet_, hwaddr_,clientid_ parameters
  1301. checkLease4(lease);
  1302. // Check that the lease is indeed updated in LeaseMgr
  1303. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(addr);
  1304. ASSERT_TRUE(from_mgr);
  1305. // Now check that the lease in LeaseMgr has the same parameters
  1306. detailCompareLease(lease, from_mgr);
  1307. }
  1308. // This test checks the behavior of the allocation engine in the following
  1309. // scenario:
  1310. // - Client has no lease in the database.
  1311. // - Client has a reservation.
  1312. // - Client sends DHCPREQUEST without requested IP Address, nor ciaddr.
  1313. // - Client is allocated a reserved address.
  1314. //
  1315. // Note that client must normally include a requested IP address or ciaddr
  1316. // in its message. But, we still want to provision clients that don't do that.
  1317. // The server simply picks reserved address or any other available one if there
  1318. // is no reservation.
  1319. TEST_F(AllocEngine4Test, reservedAddressNoHint) {
  1320. // Create reservation for the client.
  1321. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1322. Host::IDENT_HWADDR, subnet_->getID(),
  1323. SubnetID(0), IOAddress("192.0.2.123")));
  1324. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1325. CfgMgr::instance().commit();
  1326. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1327. // Try to allocate a lease without specifying a hint. This is actually
  1328. // incorrect behavior of the client to not send an address it wants to
  1329. // obtain but the server should handle this gracefully.
  1330. Lease4Ptr lease = engine.allocateLease4(subnet_, clientid_, hwaddr_,
  1331. IOAddress("0.0.0.0"),
  1332. false, false, "",
  1333. false, CalloutHandlePtr(),
  1334. old_lease_);
  1335. ASSERT_TRUE(lease);
  1336. EXPECT_EQ("192.0.2.123", lease->addr_.toText());
  1337. // Make sure that the lease has been committed to the lease database.
  1338. // And that the committed lease is equal to the one returned.
  1339. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  1340. ASSERT_TRUE(from_mgr);
  1341. detailCompareLease(lease, from_mgr);
  1342. // Initially, there was no lease for this client, so the returned old
  1343. // lease should be NULL.
  1344. EXPECT_FALSE(old_lease_);
  1345. }
  1346. // This test checks behavior of the allocation engine in the following scenario:
  1347. // - Client has no lease in the database.
  1348. // - Client has a reservation.
  1349. // - Client sends DHCPDISCOVER without requested IP Address.
  1350. // - Server returns DHCPOFFER with the reserved address.
  1351. TEST_F(AllocEngine4Test,reservedAddressNoHintFakeAllocation) {
  1352. // Create reservation for the client.
  1353. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1354. Host::IDENT_HWADDR, subnet_->getID(),
  1355. SubnetID(0), IOAddress("192.0.2.123")));
  1356. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1357. CfgMgr::instance().commit();
  1358. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1359. // Query allocation engine for the lease to be assigned to this
  1360. // client without specifying the address to be assigned.
  1361. Lease4Ptr lease = engine.allocateLease4(subnet_, clientid_, hwaddr_,
  1362. IOAddress("0.0.0.0"),
  1363. false, false, "",
  1364. true, CalloutHandlePtr(),
  1365. old_lease_);
  1366. ASSERT_TRUE(lease);
  1367. // The allocation engine should return a reserved address.
  1368. EXPECT_EQ("192.0.2.123", lease->addr_.toText());
  1369. // This is a "fake" allocation so the returned lease should not be committed
  1370. // to the lease database.
  1371. EXPECT_FALSE(LeaseMgrFactory::instance().getLease4(lease->addr_));
  1372. // Client had no lease in the database, so the old lease returned should
  1373. // be NULL.
  1374. EXPECT_FALSE(old_lease_);
  1375. }
  1376. // This test checks the behavior of the allocation engine in the following
  1377. // scenario:
  1378. // - Client has no lease in the database.
  1379. // - Client has a reservation.
  1380. // - Client sends DHCPREQUEST with a requested IP address
  1381. // - Server returns DHCPNAK when requested IP address is different than
  1382. // the reserved address. Note that the allocation engine returns NULL
  1383. // to indicate to the server that it should send DHCPNAK.
  1384. // - Server allocates a reserved address to the client when the client requests
  1385. // this address using requested IP address option.
  1386. TEST_F(AllocEngine4Test, reservedAddressHint) {
  1387. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1388. Host::IDENT_HWADDR, subnet_->getID(),
  1389. SubnetID(0), IOAddress("192.0.2.123")));
  1390. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1391. CfgMgr::instance().commit();
  1392. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1393. Lease4Ptr lease = engine.allocateLease4(subnet_, clientid_, hwaddr_,
  1394. IOAddress("192.0.2.234"),
  1395. false, false, "",
  1396. false, CalloutHandlePtr(),
  1397. old_lease_);
  1398. // The client requested a different address than reserved, so
  1399. // the allocation engine should return NULL lease. When the server
  1400. // receives a NULL lease for the client, it will send a DHCPNAK.
  1401. ASSERT_FALSE(lease);
  1402. ASSERT_FALSE(old_lease_);
  1403. // Now, request a correct address. The client should obtain it.
  1404. lease = engine.allocateLease4(subnet_, clientid_, hwaddr_,
  1405. IOAddress("192.0.2.123"),
  1406. false, false, "",
  1407. false, CalloutHandlePtr(),
  1408. old_lease_);
  1409. ASSERT_TRUE(lease);
  1410. EXPECT_EQ("192.0.2.123", lease->addr_.toText());
  1411. // Make sure that the lease has been committed to the lease database.
  1412. // And that the committed lease is equal to the one returned.
  1413. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  1414. ASSERT_TRUE(from_mgr);
  1415. detailCompareLease(lease, from_mgr);
  1416. EXPECT_FALSE(old_lease_);
  1417. }
  1418. // This test checks the behavior of the allocation engine in the following
  1419. // scenario:
  1420. // - Client has no lease in the database.
  1421. // - Client has a reservation.
  1422. // - Client sends DHCPDISCOVER with a requested IP address as a hint.
  1423. // - Server offers a reserved address, even though it is different than the
  1424. // requested address.
  1425. TEST_F(AllocEngine4Test, reservedAddressHintFakeAllocation) {
  1426. // Create a reservation for the client.
  1427. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1428. Host::IDENT_HWADDR, subnet_->getID(),
  1429. SubnetID(0), IOAddress("192.0.2.123")));
  1430. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1431. CfgMgr::instance().commit();
  1432. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1433. // Query the allocation engine for the lease to be assigned to the client
  1434. // and specify a hint being a different address than the reserved one.
  1435. Lease4Ptr lease = engine.allocateLease4(subnet_, clientid_, hwaddr_,
  1436. IOAddress("192.0.2.234"),
  1437. false, false, "",
  1438. true, CalloutHandlePtr(),
  1439. old_lease_);
  1440. ASSERT_TRUE(lease);
  1441. // Allocation engine should return reserved address.
  1442. EXPECT_EQ("192.0.2.123", lease->addr_.toText());
  1443. // This is a "fake" allocation so the returned lease should not be committed
  1444. // to the lease database.
  1445. EXPECT_FALSE(LeaseMgrFactory::instance().getLease4(lease->addr_));
  1446. EXPECT_FALSE(old_lease_);
  1447. }
  1448. // This test checks that the behavior of the allocation engine in the following
  1449. // scenario:
  1450. // - Client has a lease for the address from the dynamic pool in the database.
  1451. // - Client has a reservation for a different address than the one for which
  1452. // the client has a lease.
  1453. // - Client sends DHCPREQUEST, asking for the reserved address (as it has been
  1454. // offered to it when it sent DHCPDISCOVER).
  1455. // - Server allocates a reserved address and removes the lease for the address
  1456. // previously allocated to the client.
  1457. TEST_F(AllocEngine4Test, reservedAddressExistingLease) {
  1458. // Create the reservation for the client.
  1459. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1460. Host::IDENT_HWADDR, subnet_->getID(),
  1461. SubnetID(0), IOAddress("192.0.2.123")));
  1462. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1463. CfgMgr::instance().commit();
  1464. // Create a lease for the client with a different address than the reserved
  1465. // one.
  1466. Lease4Ptr lease(new Lease4(IOAddress("192.0.2.101"), hwaddr_, 0, 0,
  1467. 100, 30, 60, time(NULL), subnet_->getID(),
  1468. false, false, ""));
  1469. LeaseMgrFactory::instance().addLease(lease);
  1470. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1471. // Request allocation of the reserved address.
  1472. Lease4Ptr allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1473. hwaddr_,
  1474. IOAddress("192.0.2.123"),
  1475. false, false, "",
  1476. false, CalloutHandlePtr(),
  1477. old_lease_);
  1478. ASSERT_TRUE(allocated_lease);
  1479. // The engine should have allocated the reserved address.
  1480. EXPECT_EQ("192.0.2.123", allocated_lease->addr_.toText());
  1481. // Make sure that the lease has been committed to the lease database.
  1482. Lease4Ptr from_mgr =
  1483. LeaseMgrFactory::instance().getLease4(allocated_lease->addr_);
  1484. ASSERT_TRUE(from_mgr);
  1485. detailCompareLease(allocated_lease, from_mgr);
  1486. // The previous lease should have been replaced by a new one. The previous
  1487. // lease should be returned by the allocation engine to the caller.
  1488. ASSERT_TRUE(old_lease_);
  1489. EXPECT_EQ("192.0.2.101", old_lease_->addr_.toText());
  1490. detailCompareLease(old_lease_, lease);
  1491. }
  1492. // This test checks that the behavior of the allocation engine in the following
  1493. // scenario:
  1494. // - Client A has a lease in the database.
  1495. // - Client B has a reservation for the address in use by client A.
  1496. // - Client B sends a DHCPREQUEST requesting the allocation of the reserved
  1497. // lease (in use by client A).
  1498. // - Server determines that the reserved address is in use by a different client
  1499. // and returns DHCPNAK to client B.
  1500. TEST_F(AllocEngine4Test, reservedAddressHijacked) {
  1501. // Create host reservation for the client B.
  1502. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1503. Host::IDENT_HWADDR, subnet_->getID(),
  1504. SubnetID(0), IOAddress("192.0.2.123")));
  1505. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1506. CfgMgr::instance().commit();
  1507. // Allocate a lease for the client A for the same address as reserved
  1508. // for the client B.
  1509. Lease4Ptr lease(new Lease4(IOAddress("192.0.2.123"), hwaddr2_, 0, 0,
  1510. 100, 30, 60, time(NULL), subnet_->getID(),
  1511. false, false, ""));
  1512. LeaseMgrFactory::instance().addLease(lease);
  1513. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1514. // Try to allocate the reserved lease to client B.
  1515. Lease4Ptr allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1516. hwaddr_,
  1517. IOAddress("192.0.2.123"),
  1518. false, false, "",
  1519. false, CalloutHandlePtr(),
  1520. old_lease_);
  1521. // The lease is allocated to someone else, so the allocation should not
  1522. // succeed.
  1523. ASSERT_FALSE(allocated_lease);
  1524. EXPECT_FALSE(old_lease_);
  1525. // Make sure that the allocation engine didn't modify the lease of the
  1526. // client A.
  1527. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  1528. ASSERT_TRUE(from_mgr);
  1529. detailCompareLease(lease, from_mgr);
  1530. // Try doing the same thing, but this time do not request any specific
  1531. // address. It should have the same effect.
  1532. allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1533. hwaddr_,
  1534. IOAddress("0.0.0.0"),
  1535. false, false, "",
  1536. false, CalloutHandlePtr(),
  1537. old_lease_);
  1538. ASSERT_FALSE(allocated_lease);
  1539. EXPECT_FALSE(old_lease_);
  1540. from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  1541. ASSERT_TRUE(from_mgr);
  1542. detailCompareLease(lease, from_mgr);
  1543. }
  1544. // This test checks that the behavior of the allocation engine in the following
  1545. // scenario:
  1546. // - Client A has a lease in the database.
  1547. // - Client B has a reservation for the address in use by client A.
  1548. // - Client B sends a DHCPDISCOVER.
  1549. // - Server determines that the reserved address is in use by a different client
  1550. // and that it can't allocate a lease to the client B.
  1551. //
  1552. // In the scenario presented here, the allocation engine should return a
  1553. // NULL lease to the server. When the server receives NULL pointer from the
  1554. // allocation engine the proper action for the server will be to not
  1555. // respond to the client. Instead it should report to the administrator
  1556. // that it was unable to allocate the (reserved) lease.
  1557. TEST_F(AllocEngine4Test, reservedAddressHijackedFakeAllocation) {
  1558. // Create a reservation for the client B.
  1559. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1560. Host::IDENT_HWADDR, subnet_->getID(),
  1561. SubnetID(0), IOAddress("192.0.2.123")));
  1562. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1563. CfgMgr::instance().commit();
  1564. // Create a lease for the client A.
  1565. Lease4Ptr lease(new Lease4(IOAddress("192.0.2.123"), hwaddr2_, 0, 0,
  1566. 100, 30, 60, time(NULL), subnet_->getID(),
  1567. false, false, ""));
  1568. LeaseMgrFactory::instance().addLease(lease);
  1569. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1570. // Query allocation engine for the lease to be allocated to the client B.
  1571. // The allocation engine is not able to allocate the lease to the client
  1572. // B, because the address is in use by client A.
  1573. Lease4Ptr allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1574. hwaddr_,
  1575. IOAddress("192.0.2.123"),
  1576. false, false, "",
  1577. true, CalloutHandlePtr(),
  1578. old_lease_);
  1579. // The allocation engine should return no lease.
  1580. ASSERT_FALSE(allocated_lease);
  1581. EXPECT_FALSE(old_lease_);
  1582. // Do the same test. But, this time do not specify any address to be
  1583. // allocated.
  1584. allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1585. hwaddr_,
  1586. IOAddress("0.0.0.0"),
  1587. false, false, "",
  1588. true, CalloutHandlePtr(),
  1589. old_lease_);
  1590. EXPECT_FALSE(allocated_lease);
  1591. EXPECT_FALSE(old_lease_);
  1592. }
  1593. // This test checks that the behavior of the allocation engine in the following
  1594. // scenario:
  1595. // - Client has a reservation.
  1596. // - Client has a lease in the database for a different address than reserved.
  1597. // - Client sends a DHCPREQUEST and asks for a different address than reserved,
  1598. // and different than it has in a database.
  1599. // - Server doesn't allocate the reserved address to the client because the
  1600. // client asked for the different address.
  1601. //
  1602. // Note that in this case the client should get the DHCPNAK and should fall back
  1603. // to the DHCPDISCOVER.
  1604. TEST_F(AllocEngine4Test, reservedAddressExistingLeaseInvalidHint) {
  1605. // Create a reservation for the client.
  1606. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1607. Host::IDENT_HWADDR, subnet_->getID(),
  1608. SubnetID(0), IOAddress("192.0.2.123")));
  1609. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1610. CfgMgr::instance().commit();
  1611. // Create a lease for the client for a different address than reserved.
  1612. Lease4Ptr lease(new Lease4(IOAddress("192.0.2.101"), hwaddr_, 0, 0,
  1613. 100, 30, 60, time(NULL), subnet_->getID(),
  1614. false, false, ""));
  1615. LeaseMgrFactory::instance().addLease(lease);
  1616. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1617. // Try to allocate a lease and specify a different address than reserved
  1618. // and different from the one that client is currently using.
  1619. Lease4Ptr allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1620. hwaddr_,
  1621. IOAddress("192.0.2.102"),
  1622. false, false, "",
  1623. false, CalloutHandlePtr(),
  1624. old_lease_);
  1625. ASSERT_FALSE(allocated_lease);
  1626. ASSERT_FALSE(old_lease_);
  1627. // Repeat the test, but this time ask for the address that the client
  1628. // has allocated.
  1629. allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1630. hwaddr_,
  1631. IOAddress("192.0.2.101"),
  1632. false, false, "",
  1633. false, CalloutHandlePtr(),
  1634. old_lease_);
  1635. // The client has reservation so the server wants to allocate a
  1636. // reserved address and doesn't want to renew the address that the
  1637. // client is currently using. This is equivalent of the case when
  1638. // the client tries to renew the lease but there is a new reservation
  1639. // for this client. The server doesn't allow for the renewal and
  1640. // responds with DHCPNAK to force the client to return to the
  1641. // DHCP server discovery.
  1642. EXPECT_FALSE(allocated_lease);
  1643. EXPECT_FALSE(old_lease_);
  1644. }
  1645. // This test checks that the behavior of the allocation engine in the following
  1646. // scenario:
  1647. // - Client has a lease in the database.
  1648. // - Client has a reservation for a different address than the one for which it
  1649. // has a lease.
  1650. // - Client sends a DHCPDISCOVER and asks for a different address than reserved
  1651. // and different from which it has a lease for.
  1652. // - Server ignores the client's hint and offers a reserved address.
  1653. TEST_F(AllocEngine4Test, reservedAddressExistingLeaseFakeAllocation) {
  1654. // Create a reservation for the client.
  1655. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1656. Host::IDENT_HWADDR, subnet_->getID(),
  1657. SubnetID(0), IOAddress("192.0.2.123")));
  1658. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1659. CfgMgr::instance().commit();
  1660. // Create a lease for a different address than reserved.
  1661. Lease4Ptr lease(new Lease4(IOAddress("192.0.2.101"), hwaddr_, 0, 0,
  1662. 100, 30, 60, time(NULL), subnet_->getID(),
  1663. false, false, ""));
  1664. LeaseMgrFactory::instance().addLease(lease);
  1665. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1666. // Try to allocate a lease and use a completely different address
  1667. // as a hint.
  1668. Lease4Ptr allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1669. hwaddr_,
  1670. IOAddress("192.0.2.102"),
  1671. false, false, "",
  1672. true, CalloutHandlePtr(),
  1673. old_lease_);
  1674. // Server should offer a lease for a reserved address.
  1675. ASSERT_TRUE(allocated_lease);
  1676. EXPECT_EQ("192.0.2.123", allocated_lease->addr_.toText());
  1677. // The lease should not be allocated until the client sends a DHCPREQUEST.
  1678. EXPECT_FALSE(LeaseMgrFactory::instance().getLease4(allocated_lease->addr_));
  1679. // Old lease should contain the currently used lease.
  1680. ASSERT_TRUE(old_lease_);
  1681. EXPECT_EQ("192.0.2.101", old_lease_->addr_.toText());
  1682. // Repeat the test but this time ask for the address for which the
  1683. // client has a lease.
  1684. allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1685. hwaddr_,
  1686. IOAddress("192.0.2.101"),
  1687. false, false, "",
  1688. true, CalloutHandlePtr(),
  1689. old_lease_);
  1690. // The server should offer the lease, but not for the address that
  1691. // the client requested. The server should offer a reserved address.
  1692. ASSERT_TRUE(allocated_lease);
  1693. EXPECT_EQ("192.0.2.123", allocated_lease->addr_.toText());
  1694. // Old lease should contain the currently used lease.
  1695. ASSERT_TRUE(old_lease_);
  1696. EXPECT_EQ("192.0.2.101", old_lease_->addr_.toText());
  1697. }
  1698. // This test checks that the behavior of the allocation engine in the following
  1699. // scenario:
  1700. // - Client has a reservation.
  1701. // - Client has a lease for a different address than reserved.
  1702. // - Client sends a DHCPREQUEST to allocate a lease.
  1703. // - The server determines that the client has a reservation for the
  1704. // different address than it is currently using and should assign
  1705. // a reserved address and remove the previous lease.
  1706. TEST_F(AllocEngine4Test, reservedAddressExistingLeaseNoHint) {
  1707. // Create a reservation.
  1708. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1709. Host::IDENT_HWADDR, subnet_->getID(),
  1710. SubnetID(0), IOAddress("192.0.2.123")));
  1711. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1712. CfgMgr::instance().commit();
  1713. // Create a lease for a different address than reserved.
  1714. Lease4Ptr lease(new Lease4(IOAddress("192.0.2.101"), hwaddr_, 0, 0,
  1715. 100, 30, 60, time(NULL), subnet_->getID(),
  1716. false, false, ""));
  1717. LeaseMgrFactory::instance().addLease(lease);
  1718. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1719. // Try to allocate a lease with providing no hint.
  1720. Lease4Ptr allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1721. hwaddr_,
  1722. IOAddress("0.0.0.0"),
  1723. false, false, "",
  1724. false, CalloutHandlePtr(),
  1725. old_lease_);
  1726. // The reserved address should be allocated.
  1727. ASSERT_TRUE(allocated_lease);
  1728. EXPECT_EQ("192.0.2.123", allocated_lease->addr_.toText());
  1729. // The previous lease should be removed.
  1730. EXPECT_FALSE(LeaseMgrFactory::instance().getLease4(lease->addr_));
  1731. // Make sure that the allocated lease is committed in the lease database.
  1732. Lease4Ptr from_mgr =
  1733. LeaseMgrFactory::instance().getLease4(allocated_lease->addr_);
  1734. ASSERT_TRUE(from_mgr);
  1735. detailCompareLease(allocated_lease, from_mgr);
  1736. // Old lease should be returned.
  1737. ASSERT_TRUE(old_lease_);
  1738. detailCompareLease(lease, old_lease_);
  1739. }
  1740. // This test checks that the behavior of the allocation engine in the following
  1741. // scenario:
  1742. // - Client has a reservation.
  1743. // - Client has a lease for a different address than reserved.
  1744. // - Client sends a DHCPDISCOVER with no hint.
  1745. // - Server determines that there is a reservation for the client and that
  1746. // the current lease should be removed and the reserved address should be
  1747. // allocated.
  1748. TEST_F(AllocEngine4Test, reservedAddressExistingLeaseNoHintFakeAllocation) {
  1749. // Create a reservation.
  1750. HostPtr host(new Host(&hwaddr_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1751. Host::IDENT_HWADDR, subnet_->getID(),
  1752. SubnetID(0), IOAddress("192.0.2.123")));
  1753. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1754. CfgMgr::instance().commit();
  1755. // Create a lease for a different address than reserved.
  1756. Lease4Ptr lease(new Lease4(IOAddress("192.0.2.101"), hwaddr_, 0, 0,
  1757. 100, 30, 60, time(NULL), subnet_->getID(),
  1758. false, false, ""));
  1759. LeaseMgrFactory::instance().addLease(lease);
  1760. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1761. // Query the allocation engine for the lease to be allocated for the
  1762. // client.
  1763. Lease4Ptr allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1764. hwaddr_,
  1765. IOAddress("0.0.0.0"),
  1766. false, false, "",
  1767. true, CalloutHandlePtr(),
  1768. old_lease_);
  1769. // The server should offer the reserved address.
  1770. ASSERT_TRUE(allocated_lease);
  1771. EXPECT_EQ("192.0.2.123", allocated_lease->addr_.toText());
  1772. // The lease should not be committed to the lease database until the
  1773. // client sends a DHCPREQUEST.
  1774. EXPECT_FALSE(LeaseMgrFactory::instance().getLease4(allocated_lease->addr_));
  1775. // The old lease should reflect what is in the database.
  1776. ASSERT_TRUE(old_lease_);
  1777. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  1778. ASSERT_TRUE(from_mgr);
  1779. detailCompareLease(lease, from_mgr);
  1780. }
  1781. // This test checks that the behavior of the allocation engine in the following
  1782. // scenario:
  1783. // - Client A has a lease for the address.
  1784. // - Client B has a reservation for the same address that the Client A is using.
  1785. // - Client B requests allocation of the reserved address.
  1786. // - Server returns DHCPNAK to the client to indicate that the requested address
  1787. // can't be allocated.
  1788. // - Client A renews the lease.
  1789. // - Server determines that the lease that the Client A is trying to renews
  1790. // is for the address reserved for Client B. Therefore, the server returns
  1791. // DHCPNAK to force the client to return to the server discovery.
  1792. // - The Client A sends DHCPDISCOVER.
  1793. // - The server offers an address to the Client A, which is different than
  1794. // the address reserved for Client B.
  1795. // - The Client A requests allocation of the offered address.
  1796. // - The server allocates the new address to Client A.
  1797. // - The Client B sends DHCPDISCOVER to the server.
  1798. // - The server offers a reserved address to the Client B.
  1799. // - The Client B requests the offered address.
  1800. // - The server allocates the reserved address to the Client B.
  1801. TEST_F(AllocEngine4Test, reservedAddressConflictResolution) {
  1802. // Create a reservation for client B.
  1803. HostPtr host(new Host(&hwaddr2_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1804. Host::IDENT_HWADDR, subnet_->getID(),
  1805. SubnetID(0), IOAddress("192.0.2.101")));
  1806. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1807. CfgMgr::instance().commit();
  1808. // Create a lease for Client A.
  1809. Lease4Ptr lease(new Lease4(IOAddress("192.0.2.101"), hwaddr_, 0, 0,
  1810. 100, 30, 60, time(NULL), subnet_->getID(),
  1811. false, false, ""));
  1812. LeaseMgrFactory::instance().addLease(lease);
  1813. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1814. // Client B sends a DHCPREQUEST to allocate a reserved lease. The
  1815. // allocation engine declines allocation of the address for the
  1816. // client because Client A has a lease for it.
  1817. ASSERT_FALSE(engine.allocateLease4(subnet_, ClientIdPtr(), hwaddr2_,
  1818. IOAddress("192.0.2.101"), false,
  1819. false, "", false, CalloutHandlePtr(),
  1820. old_lease_));
  1821. // Client A tries to renew the lease. The renewal should fail because
  1822. // server detects that Client A doesn't have reservation for this
  1823. // address.
  1824. ASSERT_FALSE(engine.allocateLease4(subnet_, clientid_, hwaddr_,
  1825. IOAddress("192.0.2.101"), false, false,
  1826. "", false, CalloutHandlePtr(),
  1827. old_lease_));
  1828. ASSERT_TRUE(old_lease_);
  1829. EXPECT_EQ("192.0.2.101", old_lease_->addr_.toText());
  1830. // Client A returns to DHCPDISCOVER and should be offered a lease.
  1831. // The offered lease address must be different than the one the
  1832. // Client B has reservation for.
  1833. Lease4Ptr offered_lease = engine.allocateLease4(subnet_, clientid_,
  1834. hwaddr_,
  1835. IOAddress("192.0.2.101"),
  1836. false, false, "", true,
  1837. CalloutHandlePtr(),
  1838. old_lease_);
  1839. ASSERT_TRUE(offered_lease);
  1840. EXPECT_NE(offered_lease->addr_.toText(), "192.0.2.101");
  1841. // Client A tried to acquire the lease. It should succeed. At this point
  1842. // the previous lease should be released and become available for the
  1843. // Client B.
  1844. Lease4Ptr allocated_lease = engine.allocateLease4(subnet_, clientid_,
  1845. hwaddr_,
  1846. offered_lease->addr_,
  1847. false, false, "", false,
  1848. CalloutHandlePtr(),
  1849. old_lease_);
  1850. ASSERT_TRUE(allocated_lease);
  1851. EXPECT_NE(allocated_lease->addr_.toText(), "192.0.2.101");
  1852. // Client B tries to get the lease again. It should be offered
  1853. // a reserved lease.
  1854. offered_lease = engine.allocateLease4(subnet_, ClientIdPtr(),
  1855. hwaddr2_,
  1856. IOAddress("0.0.0.0"),
  1857. false, false, "", true,
  1858. CalloutHandlePtr(),
  1859. old_lease_);
  1860. ASSERT_TRUE(offered_lease);
  1861. EXPECT_EQ("192.0.2.101", offered_lease->addr_.toText());
  1862. // Client B requests allocation of the lease and it should succeed.
  1863. allocated_lease = engine.allocateLease4(subnet_, ClientIdPtr(),
  1864. hwaddr2_,
  1865. offered_lease->addr_,
  1866. false, false, "", false,
  1867. CalloutHandlePtr(),
  1868. old_lease_);
  1869. ASSERT_TRUE(allocated_lease);
  1870. EXPECT_EQ("192.0.2.101", allocated_lease->addr_.toText());
  1871. }
  1872. // This test checks that the address is not assigned from the dynamic
  1873. // pool if it has been reserved for another client.
  1874. TEST_F(AllocEngine4Test, reservedAddressVsDynamicPool) {
  1875. // Create a reservation for the client.
  1876. HostPtr host(new Host(&hwaddr2_->hwaddr_[0], hwaddr_->hwaddr_.size(),
  1877. Host::IDENT_HWADDR, subnet_->getID(),
  1878. SubnetID(0), IOAddress("192.0.2.100")));
  1879. CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(host);
  1880. CfgMgr::instance().commit();
  1881. AllocEngine engine(AllocEngine::ALLOC_ITERATIVE, 100, false);
  1882. // Different client tries to allocate a lease. Note, that we're using
  1883. // an iterative allocator which would pick the first address from the
  1884. // dynamic pool, i.e. 192.0.2.100. This address is reserved so we expect
  1885. // that a different address will be allocated.
  1886. Lease4Ptr allocated_lease = engine.allocateLease4(subnet_, ClientIdPtr(),
  1887. hwaddr_,
  1888. IOAddress("0.0.0.0"),
  1889. false, false, "", false,
  1890. CalloutHandlePtr(),
  1891. old_lease_);
  1892. ASSERT_TRUE(allocated_lease);
  1893. EXPECT_NE(allocated_lease->addr_.toText(), "192.0.2.100");
  1894. }
  1895. /// @brief helper class used in Hooks testing in AllocEngine6
  1896. ///
  1897. /// It features a couple of callout functions and buffers to store
  1898. /// the data that is accessible via callouts.
  1899. class HookAllocEngine6Test : public AllocEngine6Test {
  1900. public:
  1901. HookAllocEngine6Test() {
  1902. resetCalloutBuffers();
  1903. }
  1904. virtual ~HookAllocEngine6Test() {
  1905. HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts(
  1906. "lease6_select");
  1907. }
  1908. /// @brief clears out buffers, so callouts can store received arguments
  1909. void resetCalloutBuffers() {
  1910. callback_name_ = string("");
  1911. callback_subnet6_.reset();
  1912. callback_fake_allocation_ = false;
  1913. callback_lease6_.reset();
  1914. callback_argument_names_.clear();
  1915. callback_addr_original_ = IOAddress("::");
  1916. callback_addr_updated_ = IOAddress("::");
  1917. }
  1918. /// callback that stores received callout name and received values
  1919. static int
  1920. lease6_select_callout(CalloutHandle& callout_handle) {
  1921. callback_name_ = string("lease6_select");
  1922. callout_handle.getArgument("subnet6", callback_subnet6_);
  1923. callout_handle.getArgument("fake_allocation", callback_fake_allocation_);
  1924. callout_handle.getArgument("lease6", callback_lease6_);
  1925. callback_addr_original_ = callback_lease6_->addr_;
  1926. callback_argument_names_ = callout_handle.getArgumentNames();
  1927. return (0);
  1928. }
  1929. /// callback that overrides the lease with different values
  1930. static int
  1931. lease6_select_different_callout(CalloutHandle& callout_handle) {
  1932. // Let's call the basic callout, so it can record all parameters
  1933. lease6_select_callout(callout_handle);
  1934. // Now we need to tweak the least a bit
  1935. Lease6Ptr lease;
  1936. callout_handle.getArgument("lease6", lease);
  1937. callback_addr_updated_ = addr_override_;
  1938. lease->addr_ = callback_addr_updated_;
  1939. lease->t1_ = t1_override_;
  1940. lease->t2_ = t2_override_;
  1941. lease->preferred_lft_ = pref_override_;
  1942. lease->valid_lft_ = valid_override_;
  1943. return (0);
  1944. }
  1945. // Values to be used in callout to override lease6 content
  1946. static const IOAddress addr_override_;
  1947. static const uint32_t t1_override_;
  1948. static const uint32_t t2_override_;
  1949. static const uint32_t pref_override_;
  1950. static const uint32_t valid_override_;
  1951. // Callback will store original and overridden values here
  1952. static IOAddress callback_addr_original_;
  1953. static IOAddress callback_addr_updated_;
  1954. // Buffers (callback will store received values here)
  1955. static string callback_name_;
  1956. static Subnet6Ptr callback_subnet6_;
  1957. static Lease6Ptr callback_lease6_;
  1958. static bool callback_fake_allocation_;
  1959. static vector<string> callback_argument_names_;
  1960. };
  1961. // For some reason intialization within a class makes the linker confused.
  1962. // linker complains about undefined references if they are defined within
  1963. // the class declaration.
  1964. const IOAddress HookAllocEngine6Test::addr_override_("2001:db8::abcd");
  1965. const uint32_t HookAllocEngine6Test::t1_override_ = 6000;
  1966. const uint32_t HookAllocEngine6Test::t2_override_ = 7000;
  1967. const uint32_t HookAllocEngine6Test::pref_override_ = 8000;
  1968. const uint32_t HookAllocEngine6Test::valid_override_ = 9000;
  1969. IOAddress HookAllocEngine6Test::callback_addr_original_("::");
  1970. IOAddress HookAllocEngine6Test::callback_addr_updated_("::");
  1971. string HookAllocEngine6Test::callback_name_;
  1972. Subnet6Ptr HookAllocEngine6Test::callback_subnet6_;
  1973. Lease6Ptr HookAllocEngine6Test::callback_lease6_;
  1974. bool HookAllocEngine6Test::callback_fake_allocation_;
  1975. vector<string> HookAllocEngine6Test::callback_argument_names_;
  1976. // This test checks if the lease6_select callout is executed and expected
  1977. // parameters as passed.
  1978. TEST_F(HookAllocEngine6Test, lease6_select) {
  1979. // Note: The following order is working as expected:
  1980. // 1. create AllocEngine (that register hook points)
  1981. // 2. call loadLibraries()
  1982. //
  1983. // This order, however, causes segfault in HooksManager
  1984. // 1. call loadLibraries()
  1985. // 2. create AllocEngine (that register hook points)
  1986. // Create allocation engine (hook names are registered in its ctor)
  1987. boost::scoped_ptr<AllocEngine> engine;
  1988. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100)));
  1989. ASSERT_TRUE(engine);
  1990. // Initialize Hooks Manager
  1991. vector<string> libraries; // no libraries at this time
  1992. HooksManager::loadLibraries(libraries);
  1993. // Install pkt6_receive_callout
  1994. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1995. "lease6_select", lease6_select_callout));
  1996. CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
  1997. Lease6Ptr lease;
  1998. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  1999. duid_, iaid_, IOAddress("::"), Lease::TYPE_NA, false, false,
  2000. "", false, callout_handle, old_leases_, HWAddrPtr())));
  2001. // Check that we got a lease
  2002. ASSERT_TRUE(lease);
  2003. // Do all checks on the lease
  2004. checkLease6(lease, Lease::TYPE_NA, 128);
  2005. // Check that the lease is indeed in LeaseMgr
  2006. Lease6Ptr from_mgr = LeaseMgrFactory::instance().getLease6(lease->type_,
  2007. lease->addr_);
  2008. ASSERT_TRUE(from_mgr);
  2009. // Check that callouts were indeed called
  2010. EXPECT_EQ("lease6_select", callback_name_);
  2011. // Now check that the lease in LeaseMgr has the same parameters
  2012. ASSERT_TRUE(callback_lease6_);
  2013. detailCompareLease(callback_lease6_, from_mgr);
  2014. ASSERT_TRUE(callback_subnet6_);
  2015. EXPECT_EQ(subnet_->toText(), callback_subnet6_->toText());
  2016. EXPECT_FALSE(callback_fake_allocation_);
  2017. // Check if all expected parameters are reported. It's a bit tricky, because
  2018. // order may be different. If the test starts failing, because someone tweaked
  2019. // hooks engine, we'll have to implement proper vector matching (ignoring order)
  2020. vector<string> expected_argument_names;
  2021. expected_argument_names.push_back("fake_allocation");
  2022. expected_argument_names.push_back("lease6");
  2023. expected_argument_names.push_back("subnet6");
  2024. sort(callback_argument_names_.begin(), callback_argument_names_.end());
  2025. sort(expected_argument_names.begin(), expected_argument_names.end());
  2026. EXPECT_TRUE(callback_argument_names_ == expected_argument_names);
  2027. }
  2028. // This test checks if lease6_select callout is able to override the values
  2029. // in a lease6.
  2030. TEST_F(HookAllocEngine6Test, change_lease6_select) {
  2031. // Make sure that the overridden values are different than the ones from
  2032. // subnet originally used to create the lease
  2033. ASSERT_NE(t1_override_, subnet_->getT1());
  2034. ASSERT_NE(t2_override_, subnet_->getT2());
  2035. ASSERT_NE(pref_override_, subnet_->getPreferred());
  2036. ASSERT_NE(valid_override_, subnet_->getValid());
  2037. ASSERT_FALSE(subnet_->inRange(addr_override_));
  2038. // Create allocation engine (hook names are registered in its ctor)
  2039. boost::scoped_ptr<AllocEngine> engine;
  2040. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100)));
  2041. ASSERT_TRUE(engine);
  2042. // Initialize Hooks Manager
  2043. vector<string> libraries; // no libraries at this time
  2044. HooksManager::loadLibraries(libraries);
  2045. // Install a callout
  2046. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  2047. "lease6_select", lease6_select_different_callout));
  2048. // Normally, dhcpv6_srv would passed the handle when calling allocateLeases6,
  2049. // but in tests we need to create it on our own.
  2050. CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
  2051. // Call allocateLeases6. Callouts should be triggered here.
  2052. Lease6Ptr lease;
  2053. EXPECT_NO_THROW(lease = expectOneLease(engine->allocateLeases6(subnet_,
  2054. duid_, iaid_, IOAddress("::"), Lease::TYPE_NA, false, false,
  2055. "", false, callout_handle, old_leases_, HWAddrPtr())));
  2056. // Check that we got a lease
  2057. ASSERT_TRUE(lease);
  2058. // See if the values overridden by callout are there
  2059. EXPECT_TRUE(lease->addr_.equals(addr_override_));
  2060. EXPECT_EQ(t1_override_, lease->t1_);
  2061. EXPECT_EQ(t2_override_, lease->t2_);
  2062. EXPECT_EQ(pref_override_, lease->preferred_lft_);
  2063. EXPECT_EQ(valid_override_, lease->valid_lft_);
  2064. // Now check if the lease is in the database
  2065. Lease6Ptr from_mgr = LeaseMgrFactory::instance().getLease6(lease->type_,
  2066. lease->addr_);
  2067. ASSERT_TRUE(from_mgr);
  2068. // Check if values in the database are overridden
  2069. EXPECT_TRUE(from_mgr->addr_.equals(addr_override_));
  2070. EXPECT_EQ(t1_override_, from_mgr->t1_);
  2071. EXPECT_EQ(t2_override_, from_mgr->t2_);
  2072. EXPECT_EQ(pref_override_, from_mgr->preferred_lft_);
  2073. EXPECT_EQ(valid_override_, from_mgr->valid_lft_);
  2074. }
  2075. /// @brief helper class used in Hooks testing in AllocEngine4
  2076. ///
  2077. /// It features a couple of callout functions and buffers to store
  2078. /// the data that is accessible via callouts.
  2079. ///
  2080. /// Note: lease4_renew callout is tested from DHCPv4 server.
  2081. /// See HooksDhcpv4SrvTest.basic_lease4_renew in
  2082. /// src/bin/dhcp4/tests/dhcp4_srv_unittest.cc
  2083. class HookAllocEngine4Test : public AllocEngine4Test {
  2084. public:
  2085. HookAllocEngine4Test() {
  2086. resetCalloutBuffers();
  2087. }
  2088. virtual ~HookAllocEngine4Test() {
  2089. HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts(
  2090. "lease4_select");
  2091. }
  2092. /// @brief clears out buffers, so callouts can store received arguments
  2093. void resetCalloutBuffers() {
  2094. callback_name_ = string("");
  2095. callback_subnet4_.reset();
  2096. callback_fake_allocation_ = false;
  2097. callback_lease4_.reset();
  2098. callback_argument_names_.clear();
  2099. callback_addr_original_ = IOAddress("::");
  2100. callback_addr_updated_ = IOAddress("::");
  2101. }
  2102. /// callback that stores received callout name and received values
  2103. static int
  2104. lease4_select_callout(CalloutHandle& callout_handle) {
  2105. callback_name_ = string("lease4_select");
  2106. callout_handle.getArgument("subnet4", callback_subnet4_);
  2107. callout_handle.getArgument("fake_allocation", callback_fake_allocation_);
  2108. callout_handle.getArgument("lease4", callback_lease4_);
  2109. callback_addr_original_ = callback_lease4_->addr_;
  2110. callback_argument_names_ = callout_handle.getArgumentNames();
  2111. return (0);
  2112. }
  2113. /// callback that overrides the lease with different values
  2114. static int
  2115. lease4_select_different_callout(CalloutHandle& callout_handle) {
  2116. // Let's call the basic callout, so it can record all parameters
  2117. lease4_select_callout(callout_handle);
  2118. // Now we need to tweak the least a bit
  2119. Lease4Ptr lease;
  2120. callout_handle.getArgument("lease4", lease);
  2121. callback_addr_updated_ = addr_override_;
  2122. lease->addr_ = callback_addr_updated_;
  2123. lease->t1_ = t1_override_;
  2124. lease->t2_ = t2_override_;
  2125. lease->valid_lft_ = valid_override_;
  2126. return (0);
  2127. }
  2128. // Values to be used in callout to override lease4 content
  2129. static const IOAddress addr_override_;
  2130. static const uint32_t t1_override_;
  2131. static const uint32_t t2_override_;
  2132. static const uint32_t valid_override_;
  2133. // Callback will store original and overridden values here
  2134. static IOAddress callback_addr_original_;
  2135. static IOAddress callback_addr_updated_;
  2136. // Buffers (callback will store received values here)
  2137. static string callback_name_;
  2138. static Subnet4Ptr callback_subnet4_;
  2139. static Lease4Ptr callback_lease4_;
  2140. static bool callback_fake_allocation_;
  2141. static vector<string> callback_argument_names_;
  2142. };
  2143. // For some reason intialization within a class makes the linker confused.
  2144. // linker complains about undefined references if they are defined within
  2145. // the class declaration.
  2146. const IOAddress HookAllocEngine4Test::addr_override_("192.0.3.1");
  2147. const uint32_t HookAllocEngine4Test::t1_override_ = 4000;
  2148. const uint32_t HookAllocEngine4Test::t2_override_ = 7000;
  2149. const uint32_t HookAllocEngine4Test::valid_override_ = 9000;
  2150. IOAddress HookAllocEngine4Test::callback_addr_original_("::");
  2151. IOAddress HookAllocEngine4Test::callback_addr_updated_("::");
  2152. string HookAllocEngine4Test::callback_name_;
  2153. Subnet4Ptr HookAllocEngine4Test::callback_subnet4_;
  2154. Lease4Ptr HookAllocEngine4Test::callback_lease4_;
  2155. bool HookAllocEngine4Test::callback_fake_allocation_;
  2156. vector<string> HookAllocEngine4Test::callback_argument_names_;
  2157. // This test checks if the lease4_select callout is executed and expected
  2158. // parameters as passed.
  2159. TEST_F(HookAllocEngine4Test, lease4_select) {
  2160. // Note: The following order is working as expected:
  2161. // 1. create AllocEngine (that register hook points)
  2162. // 2. call loadLibraries()
  2163. //
  2164. // This order, however, causes segfault in HooksManager
  2165. // 1. call loadLibraries()
  2166. // 2. create AllocEngine (that register hook points)
  2167. // Create allocation engine (hook names are registered in its ctor)
  2168. boost::scoped_ptr<AllocEngine> engine;
  2169. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  2170. 100, false)));
  2171. ASSERT_TRUE(engine);
  2172. // Initialize Hooks Manager
  2173. vector<string> libraries; // no libraries at this time
  2174. HooksManager::loadLibraries(libraries);
  2175. // Install pkt4_receive_callout
  2176. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  2177. "lease4_select", lease4_select_callout));
  2178. CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
  2179. Lease4Ptr lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  2180. IOAddress("0.0.0.0"),
  2181. false, false, "",
  2182. false, callout_handle,
  2183. old_lease_);
  2184. // Check that we got a lease
  2185. ASSERT_TRUE(lease);
  2186. // Do all checks on the lease
  2187. checkLease4(lease);
  2188. // Check that the lease is indeed in LeaseMgr
  2189. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  2190. ASSERT_TRUE(from_mgr);
  2191. // Check that callouts were indeed called
  2192. EXPECT_EQ("lease4_select", callback_name_);
  2193. // Now check that the lease in LeaseMgr has the same parameters
  2194. ASSERT_TRUE(callback_lease4_);
  2195. detailCompareLease(callback_lease4_, from_mgr);
  2196. ASSERT_TRUE(callback_subnet4_);
  2197. EXPECT_EQ(subnet_->toText(), callback_subnet4_->toText());
  2198. EXPECT_EQ(callback_fake_allocation_, false);
  2199. // Check if all expected parameters are reported. It's a bit tricky, because
  2200. // order may be different. If the test starts failing, because someone tweaked
  2201. // hooks engine, we'll have to implement proper vector matching (ignoring order)
  2202. vector<string> expected_argument_names;
  2203. expected_argument_names.push_back("fake_allocation");
  2204. expected_argument_names.push_back("lease4");
  2205. expected_argument_names.push_back("subnet4");
  2206. EXPECT_TRUE(callback_argument_names_ == expected_argument_names);
  2207. }
  2208. // This test checks if lease4_select callout is able to override the values
  2209. // in a lease4.
  2210. TEST_F(HookAllocEngine4Test, change_lease4_select) {
  2211. // Make sure that the overridden values are different than the ones from
  2212. // subnet originally used to create the lease
  2213. ASSERT_NE(t1_override_, subnet_->getT1());
  2214. ASSERT_NE(t2_override_, subnet_->getT2());
  2215. ASSERT_NE(valid_override_, subnet_->getValid());
  2216. ASSERT_FALSE(subnet_->inRange(addr_override_));
  2217. // Create allocation engine (hook names are registered in its ctor)
  2218. boost::scoped_ptr<AllocEngine> engine;
  2219. ASSERT_NO_THROW(engine.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE,
  2220. 100, false)));
  2221. ASSERT_TRUE(engine);
  2222. // Initialize Hooks Manager
  2223. vector<string> libraries; // no libraries at this time
  2224. HooksManager::loadLibraries(libraries);
  2225. // Install a callout
  2226. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  2227. "lease4_select", lease4_select_different_callout));
  2228. // Normally, dhcpv4_srv would passed the handle when calling allocateLease4,
  2229. // but in tests we need to create it on our own.
  2230. CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
  2231. // Call allocateLease4. Callouts should be triggered here.
  2232. Lease4Ptr lease = engine->allocateLease4(subnet_, clientid_, hwaddr_,
  2233. IOAddress("0.0.0.0"),
  2234. false, false, "",
  2235. false, callout_handle,
  2236. old_lease_);
  2237. // Check that we got a lease
  2238. ASSERT_TRUE(lease);
  2239. // See if the values overridden by callout are there
  2240. EXPECT_TRUE(lease->addr_.equals(addr_override_));
  2241. EXPECT_EQ(t1_override_, lease->t1_);
  2242. EXPECT_EQ(t2_override_, lease->t2_);
  2243. EXPECT_EQ(valid_override_, lease->valid_lft_);
  2244. // Now check if the lease is in the database
  2245. Lease4Ptr from_mgr = LeaseMgrFactory::instance().getLease4(lease->addr_);
  2246. ASSERT_TRUE(from_mgr);
  2247. // Check if values in the database are overridden
  2248. EXPECT_TRUE(from_mgr->addr_.equals(addr_override_));
  2249. EXPECT_EQ(t1_override_, from_mgr->t1_);
  2250. EXPECT_EQ(t2_override_, from_mgr->t2_);
  2251. EXPECT_EQ(valid_override_, from_mgr->valid_lft_);
  2252. }
  2253. }; // End of anonymous namespace