alloc_engine_unittest.cc 117 KB

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