alloc_engine.cc 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750
  1. // Copyright (C) 2012-2016 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <config.h>
  7. #include <dhcp/dhcp6.h>
  8. #include <dhcp/pkt4.h>
  9. #include <dhcp/pkt6.h>
  10. #include <dhcp_ddns/ncr_msg.h>
  11. #include <dhcpsrv/alloc_engine.h>
  12. #include <dhcpsrv/alloc_engine_log.h>
  13. #include <dhcpsrv/cfgmgr.h>
  14. #include <dhcpsrv/dhcpsrv_log.h>
  15. #include <dhcpsrv/host_mgr.h>
  16. #include <dhcpsrv/host.h>
  17. #include <dhcpsrv/lease_mgr_factory.h>
  18. #include <dhcpsrv/ncr_generator.h>
  19. #include <hooks/callout_handle.h>
  20. #include <hooks/hooks_manager.h>
  21. #include <dhcpsrv/callout_handle_store.h>
  22. #include <stats/stats_mgr.h>
  23. #include <util/stopwatch.h>
  24. #include <hooks/server_hooks.h>
  25. #include <hooks/hooks_manager.h>
  26. #include <boost/foreach.hpp>
  27. #include <algorithm>
  28. #include <cstring>
  29. #include <sstream>
  30. #include <limits>
  31. #include <vector>
  32. #include <stdint.h>
  33. #include <string.h>
  34. using namespace isc::asiolink;
  35. using namespace isc::dhcp;
  36. using namespace isc::dhcp_ddns;
  37. using namespace isc::hooks;
  38. using namespace isc::stats;
  39. namespace {
  40. /// Structure that holds registered hook indexes
  41. struct AllocEngineHooks {
  42. int hook_index_lease4_select_; ///< index for "lease4_receive" hook point
  43. int hook_index_lease4_renew_; ///< index for "lease4_renew" hook point
  44. int hook_index_lease4_expire_; ///< index for "lease4_expire" hook point
  45. int hook_index_lease4_recover_;///< index for "lease4_recover" hook point
  46. int hook_index_lease6_select_; ///< index for "lease6_receive" hook point
  47. int hook_index_lease6_renew_; ///< index for "lease6_renew" hook point
  48. int hook_index_lease6_rebind_; ///< index for "lease6_rebind" hook point
  49. int hook_index_lease6_expire_; ///< index for "lease6_expire" hook point
  50. int hook_index_lease6_recover_;///< index for "lease6_recover" hook point
  51. /// Constructor that registers hook points for AllocationEngine
  52. AllocEngineHooks() {
  53. hook_index_lease4_select_ = HooksManager::registerHook("lease4_select");
  54. hook_index_lease4_renew_ = HooksManager::registerHook("lease4_renew");
  55. hook_index_lease4_expire_ = HooksManager::registerHook("lease4_expire");
  56. hook_index_lease4_recover_= HooksManager::registerHook("lease4_recover");
  57. hook_index_lease6_select_ = HooksManager::registerHook("lease6_select");
  58. hook_index_lease6_renew_ = HooksManager::registerHook("lease6_renew");
  59. hook_index_lease6_rebind_ = HooksManager::registerHook("lease6_rebind");
  60. hook_index_lease6_expire_ = HooksManager::registerHook("lease6_expire");
  61. hook_index_lease6_recover_= HooksManager::registerHook("lease6_recover");
  62. }
  63. };
  64. // Declare a Hooks object. As this is outside any function or method, it
  65. // will be instantiated (and the constructor run) when the module is loaded.
  66. // As a result, the hook indexes will be defined before any method in this
  67. // module is called.
  68. AllocEngineHooks Hooks;
  69. }; // anonymous namespace
  70. namespace isc {
  71. namespace dhcp {
  72. AllocEngine::IterativeAllocator::IterativeAllocator(Lease::Type lease_type)
  73. :Allocator(lease_type) {
  74. }
  75. isc::asiolink::IOAddress
  76. AllocEngine::IterativeAllocator::increasePrefix(const isc::asiolink::IOAddress& prefix,
  77. const uint8_t prefix_len) {
  78. if (!prefix.isV6()) {
  79. isc_throw(BadValue, "Prefix operations are for IPv6 only (attempted to "
  80. "increase prefix " << prefix << ")");
  81. }
  82. // Get a buffer holding an address.
  83. const std::vector<uint8_t>& vec = prefix.toBytes();
  84. if (prefix_len < 1 || prefix_len > 128) {
  85. isc_throw(BadValue, "Cannot increase prefix: invalid prefix length: "
  86. << prefix_len);
  87. }
  88. // Brief explanation what happens here:
  89. // http://www.youtube.com/watch?v=NFQCYpIHLNQ
  90. uint8_t n_bytes = (prefix_len - 1)/8;
  91. uint8_t n_bits = 8 - (prefix_len - n_bytes*8);
  92. uint8_t mask = 1 << n_bits;
  93. // Longer explanation: n_bytes specifies number of full bytes that are
  94. // in-prefix. They can also be used as an offset for the first byte that
  95. // is not in prefix. n_bits specifies number of bits on the last byte that
  96. // is (often partially) in prefix. For example for a /125 prefix, the values
  97. // are 15 and 3, respectively. Mask is a bitmask that has the least
  98. // significant bit from the prefix set.
  99. uint8_t packed[V6ADDRESS_LEN];
  100. // Copy the address. It must be V6, but we already checked that.
  101. std::memcpy(packed, &vec[0], V6ADDRESS_LEN);
  102. // Can we safely increase only the last byte in prefix without overflow?
  103. if (packed[n_bytes] + uint16_t(mask) < 256u) {
  104. packed[n_bytes] += mask;
  105. return (IOAddress::fromBytes(AF_INET6, packed));
  106. }
  107. // Overflow (done on uint8_t, but the sum is greater than 255)
  108. packed[n_bytes] += mask;
  109. // Deal with the overflow. Start increasing the least significant byte
  110. for (int i = n_bytes - 1; i >= 0; --i) {
  111. ++packed[i];
  112. // If we haven't overflowed (0xff->0x0) the next byte, then we are done
  113. if (packed[i] != 0) {
  114. break;
  115. }
  116. }
  117. return (IOAddress::fromBytes(AF_INET6, packed));
  118. }
  119. isc::asiolink::IOAddress
  120. AllocEngine::IterativeAllocator::pickAddress(const SubnetPtr& subnet,
  121. const DuidPtr&,
  122. const IOAddress&) {
  123. // Is this prefix allocation?
  124. bool prefix = pool_type_ == Lease::TYPE_PD;
  125. // Let's get the last allocated address. It is usually set correctly,
  126. // but there are times when it won't be (like after removing a pool or
  127. // perhaps restarting the server).
  128. IOAddress last = subnet->getLastAllocated(pool_type_);
  129. const PoolCollection& pools = subnet->getPools(pool_type_);
  130. if (pools.empty()) {
  131. isc_throw(AllocFailed, "No pools defined in selected subnet");
  132. }
  133. // first we need to find a pool the last address belongs to.
  134. PoolCollection::const_iterator it;
  135. for (it = pools.begin(); it != pools.end(); ++it) {
  136. if ((*it)->inRange(last)) {
  137. break;
  138. }
  139. }
  140. // last one was bogus for one of several reasons:
  141. // - we just booted up and that's the first address we're allocating
  142. // - a subnet was removed or other reconfiguration just completed
  143. // - perhaps allocation algorithm was changed
  144. if (it == pools.end()) {
  145. // ok to access first element directly. We checked that pools is non-empty
  146. IOAddress next = pools[0]->getFirstAddress();
  147. subnet->setLastAllocated(pool_type_, next);
  148. return (next);
  149. }
  150. // Ok, we have a pool that the last address belonged to, let's use it.
  151. IOAddress next("::");
  152. if (!prefix) {
  153. next = IOAddress::increase(last); // basically addr++
  154. } else {
  155. Pool6Ptr pool6 = boost::dynamic_pointer_cast<Pool6>(*it);
  156. if (!pool6) {
  157. // Something is gravely wrong here
  158. isc_throw(Unexpected, "Wrong type of pool: " << (*it)->toText()
  159. << " is not Pool6");
  160. }
  161. // Get the next prefix
  162. next = increasePrefix(last, pool6->getLength());
  163. }
  164. if ((*it)->inRange(next)) {
  165. // the next one is in the pool as well, so we haven't hit pool boundary yet
  166. subnet->setLastAllocated(pool_type_, next);
  167. return (next);
  168. }
  169. // We hit pool boundary, let's try to jump to the next pool and try again
  170. ++it;
  171. if (it == pools.end()) {
  172. // Really out of luck today. That was the last pool. Let's rewind
  173. // to the beginning.
  174. next = pools[0]->getFirstAddress();
  175. subnet->setLastAllocated(pool_type_, next);
  176. return (next);
  177. }
  178. // there is a next pool, let's try first address from it
  179. next = (*it)->getFirstAddress();
  180. subnet->setLastAllocated(pool_type_, next);
  181. return (next);
  182. }
  183. AllocEngine::HashedAllocator::HashedAllocator(Lease::Type lease_type)
  184. :Allocator(lease_type) {
  185. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  186. }
  187. isc::asiolink::IOAddress
  188. AllocEngine::HashedAllocator::pickAddress(const SubnetPtr&,
  189. const DuidPtr&,
  190. const IOAddress&) {
  191. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  192. }
  193. AllocEngine::RandomAllocator::RandomAllocator(Lease::Type lease_type)
  194. :Allocator(lease_type) {
  195. isc_throw(NotImplemented, "Random allocator is not implemented");
  196. }
  197. isc::asiolink::IOAddress
  198. AllocEngine::RandomAllocator::pickAddress(const SubnetPtr&,
  199. const DuidPtr&,
  200. const IOAddress&) {
  201. isc_throw(NotImplemented, "Random allocator is not implemented");
  202. }
  203. AllocEngine::AllocEngine(AllocType engine_type, uint64_t attempts,
  204. bool ipv6)
  205. : attempts_(attempts), incomplete_v4_reclamations_(0),
  206. incomplete_v6_reclamations_(0) {
  207. // Choose the basic (normal address) lease type
  208. Lease::Type basic_type = ipv6 ? Lease::TYPE_NA : Lease::TYPE_V4;
  209. // Initalize normal address allocators
  210. switch (engine_type) {
  211. case ALLOC_ITERATIVE:
  212. allocators_[basic_type] = AllocatorPtr(new IterativeAllocator(basic_type));
  213. break;
  214. case ALLOC_HASHED:
  215. allocators_[basic_type] = AllocatorPtr(new HashedAllocator(basic_type));
  216. break;
  217. case ALLOC_RANDOM:
  218. allocators_[basic_type] = AllocatorPtr(new RandomAllocator(basic_type));
  219. break;
  220. default:
  221. isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
  222. }
  223. // If this is IPv6 allocation engine, initalize also temporary addrs
  224. // and prefixes
  225. if (ipv6) {
  226. switch (engine_type) {
  227. case ALLOC_ITERATIVE:
  228. allocators_[Lease::TYPE_TA] = AllocatorPtr(new IterativeAllocator(Lease::TYPE_TA));
  229. allocators_[Lease::TYPE_PD] = AllocatorPtr(new IterativeAllocator(Lease::TYPE_PD));
  230. break;
  231. case ALLOC_HASHED:
  232. allocators_[Lease::TYPE_TA] = AllocatorPtr(new HashedAllocator(Lease::TYPE_TA));
  233. allocators_[Lease::TYPE_PD] = AllocatorPtr(new HashedAllocator(Lease::TYPE_PD));
  234. break;
  235. case ALLOC_RANDOM:
  236. allocators_[Lease::TYPE_TA] = AllocatorPtr(new RandomAllocator(Lease::TYPE_TA));
  237. allocators_[Lease::TYPE_PD] = AllocatorPtr(new RandomAllocator(Lease::TYPE_PD));
  238. break;
  239. default:
  240. isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
  241. }
  242. }
  243. // Register hook points
  244. hook_index_lease4_select_ = Hooks.hook_index_lease4_select_;
  245. hook_index_lease6_select_ = Hooks.hook_index_lease6_select_;
  246. }
  247. AllocEngine::AllocatorPtr AllocEngine::getAllocator(Lease::Type type) {
  248. std::map<Lease::Type, AllocatorPtr>::const_iterator alloc = allocators_.find(type);
  249. if (alloc == allocators_.end()) {
  250. isc_throw(BadValue, "No allocator initialized for pool type "
  251. << Lease::typeToText(type));
  252. }
  253. return (alloc->second);
  254. }
  255. template<typename ContextType>
  256. void
  257. AllocEngine::findReservationInternal(ContextType& ctx,
  258. const AllocEngine::HostGetFunc& host_get) {
  259. ctx.host_.reset();
  260. // We can only search for the reservation if a subnet has been selected.
  261. if (ctx.subnet_) {
  262. // Iterate over configured identifiers in the order of preference
  263. // and try to use each of them to search for the reservations.
  264. BOOST_FOREACH(const IdentifierPair& id_pair, ctx.host_identifiers_) {
  265. // Attempt to find a host using a specified identifier.
  266. ctx.host_ = host_get(ctx.subnet_->getID(), id_pair.first,
  267. &id_pair.second[0], id_pair.second.size());
  268. // If we found matching host, return.
  269. if (ctx.host_) {
  270. return;
  271. }
  272. }
  273. }
  274. }
  275. // ##########################################################################
  276. // # DHCPv6 lease allocation code starts here.
  277. // ##########################################################################
  278. AllocEngine::ClientContext6::ClientContext6()
  279. : subnet_(), duid_(), iaid_(0), type_(Lease::TYPE_NA), hwaddr_(),
  280. hints_(), fwd_dns_update_(false), rev_dns_update_(false), hostname_(""),
  281. callout_handle_(), fake_allocation_(false), old_leases_(), host_(),
  282. query_(), ia_rsp_(), host_identifiers_() {
  283. }
  284. AllocEngine::ClientContext6::ClientContext6(const Subnet6Ptr& subnet, const DuidPtr& duid,
  285. const uint32_t iaid,
  286. const isc::asiolink::IOAddress& hint,
  287. const Lease::Type type, const bool fwd_dns,
  288. const bool rev_dns,
  289. const std::string& hostname,
  290. const bool fake_allocation):
  291. subnet_(subnet), duid_(duid), iaid_(iaid), type_(type), hwaddr_(),
  292. hints_(), fwd_dns_update_(fwd_dns), rev_dns_update_(rev_dns),
  293. hostname_(hostname), fake_allocation_(fake_allocation),
  294. old_leases_(), host_(), query_(), ia_rsp_(), host_identifiers_() {
  295. static asiolink::IOAddress any("::");
  296. if (hint != any) {
  297. hints_.push_back(std::make_pair(hint, 128));
  298. }
  299. // callout_handle, host pointers initiated to NULL by their
  300. // respective constructors.
  301. // Initialize host identifiers.
  302. if (duid) {
  303. addHostIdentifier(Host::IDENT_DUID, duid->getDuid());
  304. }
  305. }
  306. void AllocEngine::findReservation(ClientContext6& ctx) {
  307. findReservationInternal(ctx, boost::bind(&HostMgr::get6,
  308. &HostMgr::instance(),
  309. _1, _2, _3, _4));
  310. }
  311. Lease6Collection
  312. AllocEngine::allocateLeases6(ClientContext6& ctx) {
  313. try {
  314. if (!ctx.subnet_) {
  315. isc_throw(InvalidOperation, "Subnet is required for IPv6 lease allocation");
  316. } else
  317. if (!ctx.duid_) {
  318. isc_throw(InvalidOperation, "DUID is mandatory for IPv6 lease allocation");
  319. }
  320. // Check if there are existing leases for that subnet/duid/iaid
  321. // combination.
  322. Lease6Collection leases =
  323. LeaseMgrFactory::instance().getLeases6(ctx.type_, *ctx.duid_, ctx.iaid_,
  324. ctx.subnet_->getID());
  325. // Now do the checks:
  326. // Case 1. if there are no leases, and there are reservations...
  327. // 1.1. are the reserved addresses are used by someone else?
  328. // yes: we have a problem
  329. // no: assign them => done
  330. // Case 2. if there are leases and there are no reservations...
  331. // 2.1 are the leases reserved for someone else?
  332. // yes: release them, assign something else
  333. // no: renew them => done
  334. // Case 3. if there are leases and there are reservations...
  335. // 3.1 are the leases matching reservations?
  336. // yes: renew them => done
  337. // no: release existing leases, assign new ones based on reservations
  338. // Case 4/catch-all. if there are no leases and no reservations...
  339. // assign new leases
  340. //
  341. // We could implement those checks as nested ifs, but the performance
  342. // gain would be minimal and the code readibility loss would be substantial.
  343. // Hence independent checks.
  344. // Case 1: There are no leases and there's a reservation for this host.
  345. if (leases.empty() && ctx.host_) {
  346. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  347. ALLOC_ENGINE_V6_ALLOC_NO_LEASES_HR)
  348. .arg(ctx.query_->getLabel());
  349. // Try to allocate leases that match reservations. Typically this will
  350. // succeed, except cases where the reserved addresses are used by
  351. // someone else.
  352. allocateReservedLeases6(ctx, leases);
  353. // If we got at least one lease, we're good to go.
  354. if (!leases.empty()) {
  355. return (leases);
  356. }
  357. // If not, we'll need to continue and will eventually fall into case 4:
  358. // getting a regular lease. That could happen when we're processing
  359. // request from client X, there's a reserved address A for X, but
  360. // A is currently used by client Y. We can't immediately reassign A
  361. // from X to Y, because Y keeps using it, so X would send Decline right
  362. // away. Need to wait till Y renews, then we can release A, so it
  363. // will become available for X.
  364. // Case 2: There are existing leases and there are no reservations.
  365. //
  366. // There is at least one lease for this client and there are no reservations.
  367. // We will return these leases for the client, but we may need to update
  368. // FQDN information.
  369. } else if (!leases.empty() && !ctx.host_) {
  370. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  371. ALLOC_ENGINE_V6_ALLOC_LEASES_NO_HR)
  372. .arg(ctx.query_->getLabel());
  373. // Check if the existing leases are reserved for someone else.
  374. // If they're not, we're ok to keep using them.
  375. removeNonmatchingReservedLeases6(ctx, leases);
  376. if (!leases.empty()) {
  377. // Return old leases so the server can see what has changed.
  378. return (updateLeaseData(ctx, leases));
  379. }
  380. // If leases are empty at this stage, it means that we used to have
  381. // leases for this client, but we checked and those leases are reserved
  382. // for someone else, so we lost them. We will need to continue and
  383. // will finally end up in case 4 (no leases, no reservations), so we'll
  384. // assign something new.
  385. // Case 3: There are leases and there are reservations.
  386. } else if (!leases.empty() && ctx.host_) {
  387. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  388. ALLOC_ENGINE_V6_ALLOC_LEASES_HR)
  389. .arg(ctx.query_->getLabel());
  390. // First, check if have leases matching reservations, and add new
  391. // leases if we don't have them.
  392. allocateReservedLeases6(ctx, leases);
  393. // leases now contain both existing and new leases that were created
  394. // from reservations.
  395. // Second, let's remove leases that are reserved for someone else.
  396. // This applies to any existing leases. This will not happen frequently,
  397. // but it may happen with the following chain of events:
  398. // 1. client A gets address X;
  399. // 2. reservation for client B for address X is made by a administrator;
  400. // 3. client A reboots
  401. // 4. client A requests the address (X) he got previously
  402. removeNonmatchingReservedLeases6(ctx, leases);
  403. // leases now contain existing and new leases, but we removed those
  404. // leases that are reserved for someone else (non-matching reserved).
  405. // There's one more check to do. Let's remove leases that are not
  406. // matching reservations, i.e. if client X has address A, but there's
  407. // a reservation for address B, we should release A and reassign B.
  408. // Caveat: do this only if we have at least one reserved address.
  409. removeNonreservedLeases6(ctx, leases);
  410. // All checks are done. Let's hope we have some leases left.
  411. // If we have any leases left, let's return them and we're done.
  412. if (!leases.empty()) {
  413. return (leases);
  414. }
  415. // If we don't have any leases at this stage, it means that we hit
  416. // one of the following cases:
  417. // - we have a reservation, but it's not for this IAID/ia-type and
  418. // we had to return the address we were using
  419. // - we have a reservation for this iaid/ia-type, but the reserved
  420. // address is currently used by someone else. We can't assign it
  421. // yet.
  422. // - we had an address, but we just discovered that it's reserved for
  423. // someone else, so we released it.
  424. }
  425. // Case 4/catch-all: One of the following is true:
  426. // - we don't have leases and there are no reservations
  427. // - we used to have leases, but we lost them, because they are now
  428. // reserved for someone else
  429. // - we have a reservation, but it is not usable yet, because the address
  430. // is still used by someone else
  431. //
  432. // In any case, we need to go through normal lease assignment process
  433. // for now. This is also a catch-all or last resort approach, when we
  434. // couldn't find any reservations (or couldn't use them).
  435. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  436. ALLOC_ENGINE_V6_ALLOC_UNRESERVED)
  437. .arg(ctx.query_->getLabel());
  438. leases = allocateUnreservedLeases6(ctx);
  439. if (!leases.empty()) {
  440. return (leases);
  441. }
  442. } catch (const isc::Exception& e) {
  443. // Some other error, return an empty lease.
  444. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_ALLOC_ERROR)
  445. .arg(ctx.query_->getLabel())
  446. .arg(e.what());
  447. }
  448. return (Lease6Collection());
  449. }
  450. Lease6Collection
  451. AllocEngine::allocateUnreservedLeases6(ClientContext6& ctx) {
  452. AllocatorPtr allocator = getAllocator(ctx.type_);
  453. if (!allocator) {
  454. isc_throw(InvalidOperation, "No allocator specified for "
  455. << Lease6::typeToText(ctx.type_));
  456. }
  457. // Check which host reservation mode is supported in this subnet.
  458. Subnet::HRMode hr_mode = ctx.subnet_->getHostReservationMode();
  459. Lease6Collection leases;
  460. IOAddress hint = IOAddress::IPV6_ZERO_ADDRESS();
  461. if (!ctx.hints_.empty()) {
  462. /// @todo: We support only one hint for now
  463. hint = ctx.hints_[0].first;
  464. }
  465. // check if the hint is in pool and is available
  466. // This is equivalent of subnet->inPool(hint), but returns the pool
  467. Pool6Ptr pool = boost::dynamic_pointer_cast<
  468. Pool6>(ctx.subnet_->getPool(ctx.type_, hint, false));
  469. if (pool) {
  470. /// @todo: We support only one hint for now
  471. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(ctx.type_, hint);
  472. if (!lease) {
  473. // In-pool reservations: Check if this address is reserved for someone
  474. // else. There is no need to check for whom it is reserved, because if
  475. // it has been reserved for us we would have already allocated a lease.
  476. ConstHostPtr host;
  477. if (hr_mode != Subnet::HR_DISABLED) {
  478. host = HostMgr::instance().get6(ctx.subnet_->getID(), hint);
  479. }
  480. if (!host) {
  481. // If the in-pool reservations are disabled, or there is no
  482. // reservation for a given hint, we're good to go.
  483. // The hint is valid and not currently used, let's create a
  484. // lease for it
  485. lease = createLease6(ctx, hint, pool->getLength());
  486. // It can happen that the lease allocation failed (we could
  487. // have lost the race condition. That means that the hint is
  488. // no longer usable and we need to continue the regular
  489. // allocation path.
  490. if (lease) {
  491. /// @todo: We support only one lease per ia for now
  492. Lease6Collection collection;
  493. collection.push_back(lease);
  494. return (collection);
  495. }
  496. } else {
  497. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  498. ALLOC_ENGINE_V6_HINT_RESERVED)
  499. .arg(ctx.query_->getLabel())
  500. .arg(hint.toText());
  501. }
  502. } else {
  503. // If the lease is expired, we may likely reuse it, but...
  504. if (lease->expired()) {
  505. ConstHostPtr host;
  506. if (hr_mode != Subnet::HR_DISABLED) {
  507. host = HostMgr::instance().get6(ctx.subnet_->getID(), hint);
  508. }
  509. // Let's check if there is a reservation for this address.
  510. if (!host) {
  511. // Copy an existing, expired lease so as it can be returned
  512. // to the caller.
  513. Lease6Ptr old_lease(new Lease6(*lease));
  514. ctx.old_leases_.push_back(old_lease);
  515. /// We found a lease and it is expired, so we can reuse it
  516. lease = reuseExpiredLease(lease, ctx, pool->getLength());
  517. /// @todo: We support only one lease per ia for now
  518. leases.push_back(lease);
  519. return (leases);
  520. } else {
  521. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  522. ALLOC_ENGINE_V6_EXPIRED_HINT_RESERVED)
  523. .arg(ctx.query_->getLabel())
  524. .arg(hint.toText());
  525. }
  526. }
  527. }
  528. }
  529. // The hint was useless (it was not provided at all, was used by someone else,
  530. // was out of pool or reserved for someone else). Search the pool until first
  531. // of the following occurs:
  532. // - we find a free address
  533. // - we find an address for which the lease has expired
  534. // - we exhaust number of tries
  535. uint64_t max_attempts = (attempts_ > 0 ? attempts_ :
  536. ctx.subnet_->getPoolCapacity(ctx.type_));
  537. for (uint64_t i = 0; i < max_attempts; ++i)
  538. {
  539. IOAddress candidate = allocator->pickAddress(ctx.subnet_, ctx.duid_, hint);
  540. /// In-pool reservations: Check if this address is reserved for someone
  541. /// else. There is no need to check for whom it is reserved, because if
  542. /// it has been reserved for us we would have already allocated a lease.
  543. if (hr_mode == Subnet::HR_ALL &&
  544. HostMgr::instance().get6(ctx.subnet_->getID(), candidate)) {
  545. // Don't allocate.
  546. continue;
  547. }
  548. // The first step is to find out prefix length. It is 128 for
  549. // non-PD leases.
  550. uint8_t prefix_len = 128;
  551. if (ctx.type_ == Lease::TYPE_PD) {
  552. Pool6Ptr pool = boost::dynamic_pointer_cast<Pool6>(
  553. ctx.subnet_->getPool(ctx.type_, candidate, false));
  554. /// @todo: verify that the pool is non-null
  555. prefix_len = pool->getLength();
  556. }
  557. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(ctx.type_,
  558. candidate);
  559. if (!existing) {
  560. // there's no existing lease for selected candidate, so it is
  561. // free. Let's allocate it.
  562. Lease6Ptr lease = createLease6(ctx, candidate, prefix_len);
  563. if (lease) {
  564. // We are allocating a new lease (not renewing). So, the
  565. // old lease should be NULL.
  566. ctx.old_leases_.clear();
  567. leases.push_back(lease);
  568. return (leases);
  569. }
  570. // Although the address was free just microseconds ago, it may have
  571. // been taken just now. If the lease insertion fails, we continue
  572. // allocation attempts.
  573. } else {
  574. if (existing->expired()) {
  575. // Copy an existing, expired lease so as it can be returned
  576. // to the caller.
  577. Lease6Ptr old_lease(new Lease6(*existing));
  578. ctx.old_leases_.push_back(old_lease);
  579. existing = reuseExpiredLease(existing,
  580. ctx,
  581. prefix_len);
  582. leases.push_back(existing);
  583. return (leases);
  584. }
  585. }
  586. }
  587. // Unable to allocate an address, return an empty lease.
  588. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V6_ALLOC_FAIL)
  589. .arg(ctx.query_->getLabel())
  590. .arg(max_attempts);
  591. // We failed to allocate anything. Let's return empty collection.
  592. return (Lease6Collection());
  593. }
  594. void
  595. AllocEngine::allocateReservedLeases6(ClientContext6& ctx, Lease6Collection& existing_leases) {
  596. // If there are no reservations or the reservation is v4, there's nothing to do.
  597. if (!ctx.host_ || !ctx.host_->hasIPv6Reservation()) {
  598. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  599. ALLOC_ENGINE_V6_ALLOC_NO_V6_HR)
  600. .arg(ctx.query_->getLabel());
  601. return;
  602. }
  603. // Let's convert this from Lease::Type to IPv6Reserv::Type
  604. IPv6Resrv::Type type = ctx.type_ == Lease::TYPE_NA ? IPv6Resrv::TYPE_NA : IPv6Resrv::TYPE_PD;
  605. // Get the IPv6 reservations of specified type.
  606. const IPv6ResrvRange& reservs = ctx.host_->getIPv6Reservations(type);
  607. for (IPv6ResrvIterator resv = reservs.first; resv != reservs.second; ++resv) {
  608. // We do have a reservation for addr.
  609. IOAddress addr = resv->second.getPrefix();
  610. uint8_t prefix_len = resv->second.getPrefixLen();
  611. // Check if already have this lease on the existing_leases list.
  612. for (Lease6Collection::iterator l = existing_leases.begin();
  613. l != existing_leases.end(); ++l) {
  614. // Ok, we already have a lease for this reservation and it's usable
  615. if (((*l)->addr_ == addr) && (*l)->valid_lft_ != 0) {
  616. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  617. ALLOC_ENGINE_V6_ALLOC_HR_LEASE_EXISTS)
  618. .arg(ctx.query_->getLabel())
  619. .arg((*l)->typeToText((*l)->type_))
  620. .arg((*l)->addr_.toText());
  621. // If this is a real allocation, we may need to extend the lease
  622. // lifetime.
  623. if (!ctx.fake_allocation_ && conditionalExtendLifetime(**l)) {
  624. LeaseMgrFactory::instance().updateLease6(*l);
  625. }
  626. return;
  627. }
  628. }
  629. // If there's a lease for this address, let's not create it.
  630. // It doesn't matter whether it is for this client or for someone else.
  631. if (!LeaseMgrFactory::instance().getLease6(ctx.type_, addr)) {
  632. // Ok, let's create a new lease...
  633. Lease6Ptr lease = createLease6(ctx, addr, prefix_len);
  634. // ... and add it to the existing leases list.
  635. existing_leases.push_back(lease);
  636. if (ctx.type_ == Lease::TYPE_NA) {
  637. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_HR_ADDR_GRANTED)
  638. .arg(addr.toText())
  639. .arg(ctx.query_->getLabel());
  640. } else {
  641. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_HR_PREFIX_GRANTED)
  642. .arg(addr.toText())
  643. .arg(static_cast<int>(prefix_len))
  644. .arg(ctx.query_->getLabel());
  645. }
  646. // We found a lease for this client and this IA. Let's return.
  647. // Returning after the first lease was assigned is useful if we
  648. // have multiple reservations for the same client. If the client
  649. // sends 2 IAs, the first time we call allocateReservedLeases6 will
  650. // use the first reservation and return. The second time, we'll
  651. // go over the first reservation, but will discover that there's
  652. // a lease corresponding to it and will skip it and then pick
  653. // the second reservation and turn it into the lease. This approach
  654. // would work for any number of reservations.
  655. return;
  656. }
  657. }
  658. }
  659. void
  660. AllocEngine::removeNonmatchingReservedLeases6(ClientContext6& ctx,
  661. Lease6Collection& existing_leases) {
  662. // If there are no leases (so nothing to remove) or
  663. // host reservation is disabled (so there are no reserved leases),
  664. // just return.
  665. if (existing_leases.empty() || !ctx.subnet_ ||
  666. (ctx.subnet_->getHostReservationMode() == Subnet::HR_DISABLED) ) {
  667. return;
  668. }
  669. // We need a copy, so we won't be iterating over a container and
  670. // removing from it at the same time. It's only a copy of pointers,
  671. // so the operation shouldn't be that expensive.
  672. Lease6Collection copy = existing_leases;
  673. for (Lease6Collection::const_iterator candidate = copy.begin();
  674. candidate != copy.end(); ++candidate) {
  675. ConstHostPtr host = HostMgr::instance().get6(ctx.subnet_->getID(),
  676. (*candidate)->addr_);
  677. if (!host || (host == ctx.host_)) {
  678. // Not reserved or reserved for us. That's ok, let's check
  679. // the next lease.
  680. continue;
  681. }
  682. // Ok, we have a problem. This host has a lease that is reserved
  683. // for someone else. We need to recover from this.
  684. if (ctx.type_ == Lease::TYPE_NA) {
  685. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_REVOKED_ADDR_LEASE)
  686. .arg((*candidate)->addr_.toText()).arg(ctx.duid_->toText())
  687. .arg(host->getIdentifierAsText());
  688. } else {
  689. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_REVOKED_PREFIX_LEASE)
  690. .arg((*candidate)->addr_.toText())
  691. .arg(static_cast<int>((*candidate)->prefixlen_))
  692. .arg(ctx.duid_->toText())
  693. .arg(host->getIdentifierAsText());
  694. }
  695. // Remove this lease from LeaseMgr
  696. LeaseMgrFactory::instance().deleteLease((*candidate)->addr_);
  697. // Update DNS if needed.
  698. queueNCR(CHG_REMOVE, *candidate);
  699. // Need to decrease statistic for assigned addresses.
  700. StatsMgr::instance().addValue(
  701. StatsMgr::generateName("subnet", ctx.subnet_->getID(),
  702. ctx.type_ == Lease::TYPE_NA ? "assigned-nas" :
  703. "assigned-pds"),
  704. static_cast<int64_t>(-1));
  705. // In principle, we could trigger a hook here, but we will do this
  706. // only if we get serious complaints from actual users. We want the
  707. // conflict resolution procedure to really work and user libraries
  708. // should not interfere with it.
  709. // Add this to the list of removed leases.
  710. ctx.old_leases_.push_back(*candidate);
  711. // Let's remove this candidate from existing leases
  712. removeLeases(existing_leases, (*candidate)->addr_);
  713. }
  714. }
  715. bool
  716. AllocEngine::removeLeases(Lease6Collection& container, const asiolink::IOAddress& addr) {
  717. bool removed = false;
  718. for (Lease6Collection::iterator lease = container.begin();
  719. lease != container.end(); ++lease) {
  720. if ((*lease)->addr_ == addr) {
  721. lease->reset();
  722. removed = true;
  723. }
  724. }
  725. // Remove all elements that have NULL value
  726. container.erase(std::remove(container.begin(), container.end(), Lease6Ptr()),
  727. container.end());
  728. return (removed);
  729. }
  730. void
  731. AllocEngine::removeNonreservedLeases6(ClientContext6& ctx,
  732. Lease6Collection& existing_leases) {
  733. // This method removes leases that are not reserved for this host.
  734. // It will keep at least one lease, though.
  735. if (existing_leases.empty() || !ctx.host_ || !ctx.host_->hasIPv6Reservation()) {
  736. return;
  737. }
  738. // This is the total number of leases. We should not remove the last one.
  739. int total = existing_leases.size();
  740. // This is officially not scary code anymore. iterates and marks specified
  741. // leases for deletion, by setting appropriate pointers to NULL.
  742. for (Lease6Collection::iterator lease = existing_leases.begin();
  743. lease != existing_leases.end(); ++lease) {
  744. IPv6Resrv resv(ctx.type_ == Lease::TYPE_NA ? IPv6Resrv::TYPE_NA : IPv6Resrv::TYPE_PD,
  745. (*lease)->addr_, (*lease)->prefixlen_);
  746. if (!ctx.host_->hasReservation(resv)) {
  747. // We have reservations, but not for this lease. Release it.
  748. // Remove this lease from LeaseMgr
  749. LeaseMgrFactory::instance().deleteLease((*lease)->addr_);
  750. // Update DNS if required.
  751. queueNCR(CHG_REMOVE, *lease);
  752. // Need to decrease statistic for assigned addresses.
  753. StatsMgr::instance().addValue(
  754. StatsMgr::generateName("subnet", ctx.subnet_->getID(),
  755. ctx.type_ == Lease::TYPE_NA ? "assigned-nas" :
  756. "assigned-pds"),
  757. static_cast<int64_t>(-1));
  758. /// @todo: Probably trigger a hook here
  759. // Add this to the list of removed leases.
  760. ctx.old_leases_.push_back(*lease);
  761. // Set this pointer to NULL. The pointer is still valid. We're just
  762. // setting the Lease6Ptr to NULL value. We'll remove all NULL
  763. // pointers once the loop is finished.
  764. lease->reset();
  765. if (--total == 1) {
  766. // If there's only one lease left, break the loop.
  767. break;
  768. }
  769. }
  770. }
  771. // Remove all elements that we previously marked for deletion (those that
  772. // have NULL value).
  773. existing_leases.erase(std::remove(existing_leases.begin(),
  774. existing_leases.end(), Lease6Ptr()), existing_leases.end());
  775. }
  776. Lease6Ptr
  777. AllocEngine::reuseExpiredLease(Lease6Ptr& expired, ClientContext6& ctx,
  778. uint8_t prefix_len) {
  779. if (!expired->expired()) {
  780. isc_throw(BadValue, "Attempt to recycle lease that is still valid");
  781. }
  782. if (expired->type_ != Lease::TYPE_PD) {
  783. prefix_len = 128; // non-PD lease types must be always /128
  784. }
  785. if (!ctx.fake_allocation_) {
  786. // The expired lease needs to be reclaimed before it can be reused.
  787. // This includes declined leases for which probation period has
  788. // elapsed.
  789. reclaimExpiredLease(expired, ctx.callout_handle_);
  790. }
  791. // address, lease type and prefixlen (0) stay the same
  792. expired->iaid_ = ctx.iaid_;
  793. expired->duid_ = ctx.duid_;
  794. expired->preferred_lft_ = ctx.subnet_->getPreferred();
  795. expired->valid_lft_ = ctx.subnet_->getValid();
  796. expired->t1_ = ctx.subnet_->getT1();
  797. expired->t2_ = ctx.subnet_->getT2();
  798. expired->cltt_ = time(NULL);
  799. expired->subnet_id_ = ctx.subnet_->getID();
  800. expired->hostname_ = ctx.hostname_;
  801. expired->fqdn_fwd_ = ctx.fwd_dns_update_;
  802. expired->fqdn_rev_ = ctx.rev_dns_update_;
  803. expired->prefixlen_ = prefix_len;
  804. expired->state_ = Lease::STATE_DEFAULT;
  805. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA,
  806. ALLOC_ENGINE_V6_REUSE_EXPIRED_LEASE_DATA)
  807. .arg(ctx.query_->getLabel())
  808. .arg(expired->toText());
  809. // Let's execute all callouts registered for lease6_select
  810. if (ctx.callout_handle_ &&
  811. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  812. // Delete all previous arguments
  813. ctx.callout_handle_->deleteAllArguments();
  814. // Pass necessary arguments
  815. // Subnet from which we do the allocation
  816. ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
  817. // Is this solicit (fake = true) or request (fake = false)
  818. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  819. // The lease that will be assigned to a client
  820. ctx.callout_handle_->setArgument("lease6", expired);
  821. // Call the callouts
  822. HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
  823. // Callouts decided to skip the action. This means that the lease is not
  824. // assigned, so the client will get NoAddrAvail as a result. The lease
  825. // won't be inserted into the database.
  826. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  827. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  828. return (Lease6Ptr());
  829. }
  830. /// @todo: Add support for DROP status
  831. // Let's use whatever callout returned. Hopefully it is the same lease
  832. // we handed to it.
  833. ctx.callout_handle_->getArgument("lease6", expired);
  834. }
  835. if (!ctx.fake_allocation_) {
  836. // for REQUEST we do update the lease
  837. LeaseMgrFactory::instance().updateLease6(expired);
  838. }
  839. // We do nothing for SOLICIT. We'll just update database when
  840. // the client gets back to us with REQUEST message.
  841. // it's not really expired at this stage anymore - let's return it as
  842. // an updated lease
  843. return (expired);
  844. }
  845. Lease6Ptr AllocEngine::createLease6(ClientContext6& ctx,
  846. const IOAddress& addr,
  847. uint8_t prefix_len) {
  848. if (ctx.type_ != Lease::TYPE_PD) {
  849. prefix_len = 128; // non-PD lease types must be always /128
  850. }
  851. Lease6Ptr lease(new Lease6(ctx.type_, addr, ctx.duid_, ctx.iaid_,
  852. ctx.subnet_->getPreferred(), ctx.subnet_->getValid(),
  853. ctx.subnet_->getT1(), ctx.subnet_->getT2(),
  854. ctx.subnet_->getID(), ctx.hwaddr_, prefix_len));
  855. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  856. lease->fqdn_rev_ = ctx.rev_dns_update_;
  857. lease->hostname_ = ctx.hostname_;
  858. // Let's execute all callouts registered for lease6_select
  859. if (ctx.callout_handle_ &&
  860. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  861. // Delete all previous arguments
  862. ctx.callout_handle_->deleteAllArguments();
  863. // Pass necessary arguments
  864. // Subnet from which we do the allocation
  865. ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
  866. // Is this solicit (fake = true) or request (fake = false)
  867. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  868. ctx.callout_handle_->setArgument("lease6", lease);
  869. // This is the first callout, so no need to clear any arguments
  870. HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
  871. // Callouts decided to skip the action. This means that the lease is not
  872. // assigned, so the client will get NoAddrAvail as a result. The lease
  873. // won't be inserted into the database.
  874. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  875. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  876. return (Lease6Ptr());
  877. }
  878. // Let's use whatever callout returned. Hopefully it is the same lease
  879. // we handed to it.
  880. ctx.callout_handle_->getArgument("lease6", lease);
  881. }
  882. if (!ctx.fake_allocation_) {
  883. // That is a real (REQUEST) allocation
  884. bool status = LeaseMgrFactory::instance().addLease(lease);
  885. if (status) {
  886. // The lease insertion succeeded - if the lease is in the
  887. // current subnet lets bump up the statistic.
  888. if (ctx.subnet_->inPool(ctx.type_, addr)) {
  889. StatsMgr::instance().addValue(
  890. StatsMgr::generateName("subnet", ctx.subnet_->getID(),
  891. ctx.type_ == Lease::TYPE_NA ? "assigned-nas" :
  892. "assigned-pds"),
  893. static_cast<int64_t>(1));
  894. }
  895. return (lease);
  896. } else {
  897. // One of many failures with LeaseMgr (e.g. lost connection to the
  898. // database, database failed etc.). One notable case for that
  899. // is that we are working in multi-process mode and we lost a race
  900. // (some other process got that address first)
  901. return (Lease6Ptr());
  902. }
  903. } else {
  904. // That is only fake (SOLICIT without rapid-commit) allocation
  905. // It is for advertise only. We should not insert the lease into LeaseMgr,
  906. // but rather check that we could have inserted it.
  907. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(
  908. Lease::TYPE_NA, addr);
  909. if (!existing) {
  910. return (lease);
  911. } else {
  912. return (Lease6Ptr());
  913. }
  914. }
  915. }
  916. Lease6Collection
  917. AllocEngine::renewLeases6(ClientContext6& ctx) {
  918. try {
  919. if (!ctx.subnet_) {
  920. isc_throw(InvalidOperation, "Subnet is required for allocation");
  921. }
  922. if (!ctx.duid_) {
  923. isc_throw(InvalidOperation, "DUID is mandatory for allocation");
  924. }
  925. // Check if there are any leases for this client.
  926. Lease6Collection leases = LeaseMgrFactory::instance()
  927. .getLeases6(ctx.type_, *ctx.duid_, ctx.iaid_, ctx.subnet_->getID());
  928. if (!leases.empty()) {
  929. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  930. ALLOC_ENGINE_V6_RENEW_REMOVE_RESERVED)
  931. .arg(ctx.query_->getLabel());
  932. // Check if the existing leases are reserved for someone else.
  933. // If they're not, we're ok to keep using them.
  934. removeNonmatchingReservedLeases6(ctx, leases);
  935. }
  936. if (ctx.host_) {
  937. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  938. ALLOC_ENGINE_V6_RENEW_HR)
  939. .arg(ctx.query_->getLabel());
  940. // If we have host reservation, allocate those leases.
  941. allocateReservedLeases6(ctx, leases);
  942. // There's one more check to do. Let's remove leases that are not
  943. // matching reservations, i.e. if client X has address A, but there's
  944. // a reservation for address B, we should release A and reassign B.
  945. // Caveat: do this only if we have at least one reserved address.
  946. removeNonreservedLeases6(ctx, leases);
  947. }
  948. // If we happen to removed all leases, get something new for this guy.
  949. // Depending on the configuration, we may enable or disable granting
  950. // new leases during renewals. This is controlled with the
  951. // allow_new_leases_in_renewals_ field.
  952. if (leases.empty()) {
  953. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  954. ALLOC_ENGINE_V6_EXTEND_ALLOC_UNRESERVED)
  955. .arg(ctx.query_->getLabel());
  956. leases = allocateUnreservedLeases6(ctx);
  957. }
  958. // Extend all existing leases that passed all checks.
  959. for (Lease6Collection::iterator l = leases.begin(); l != leases.end(); ++l) {
  960. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL,
  961. ALLOC_ENGINE_V6_EXTEND_LEASE)
  962. .arg(ctx.query_->getLabel())
  963. .arg((*l)->typeToText((*l)->type_))
  964. .arg((*l)->addr_);
  965. extendLease6(ctx, *l);
  966. }
  967. return (leases);
  968. } catch (const isc::Exception& e) {
  969. // Some other error, return an empty lease.
  970. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_EXTEND_ERROR)
  971. .arg(ctx.query_->getLabel())
  972. .arg(e.what());
  973. }
  974. return (Lease6Collection());
  975. }
  976. void
  977. AllocEngine::extendLease6(ClientContext6& ctx, Lease6Ptr lease) {
  978. if (!lease || !ctx.subnet_) {
  979. return;
  980. }
  981. // Check if the lease still belongs to the subnet. If it doesn't,
  982. // we'll need to remove it.
  983. if ((lease->type_ != Lease::TYPE_PD) && !ctx.subnet_->inRange(lease->addr_)) {
  984. // Oh dear, the lease is no longer valid. We need to get rid of it.
  985. // Remove this lease from LeaseMgr
  986. LeaseMgrFactory::instance().deleteLease(lease->addr_);
  987. // Updated DNS if required.
  988. queueNCR(CHG_REMOVE, lease);
  989. // Need to decrease statistic for assigned addresses.
  990. StatsMgr::instance().addValue(
  991. StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-nas"),
  992. static_cast<int64_t>(-1));
  993. // Add it to the removed leases list.
  994. ctx.old_leases_.push_back(lease);
  995. return;
  996. }
  997. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA,
  998. ALLOC_ENGINE_V6_EXTEND_LEASE_DATA)
  999. .arg(ctx.query_->getLabel())
  1000. .arg(lease->toText());
  1001. // Keep the old data in case the callout tells us to skip update.
  1002. Lease6Ptr old_data(new Lease6(*lease));
  1003. lease->preferred_lft_ = ctx.subnet_->getPreferred();
  1004. lease->valid_lft_ = ctx.subnet_->getValid();
  1005. lease->t1_ = ctx.subnet_->getT1();
  1006. lease->t2_ = ctx.subnet_->getT2();
  1007. lease->hostname_ = ctx.hostname_;
  1008. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  1009. lease->fqdn_rev_ = ctx.rev_dns_update_;
  1010. lease->hwaddr_ = ctx.hwaddr_;
  1011. lease->state_ = Lease::STATE_DEFAULT;
  1012. // Extend lease lifetime if it is time to extend it.
  1013. conditionalExtendLifetime(*lease);
  1014. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA,
  1015. ALLOC_ENGINE_V6_EXTEND_NEW_LEASE_DATA)
  1016. .arg(ctx.query_->getLabel())
  1017. .arg(lease->toText());
  1018. bool skip = false;
  1019. // Get the callouts specific for the processed message and execute them.
  1020. int hook_point = ctx.query_->getType() == DHCPV6_RENEW ?
  1021. Hooks.hook_index_lease6_renew_ : Hooks.hook_index_lease6_rebind_;
  1022. if (HooksManager::calloutsPresent(hook_point)) {
  1023. CalloutHandlePtr callout_handle = ctx.callout_handle_;
  1024. // Delete all previous arguments
  1025. callout_handle->deleteAllArguments();
  1026. // Pass the original packet
  1027. callout_handle->setArgument("query6", ctx.query_);
  1028. // Pass the lease to be updated
  1029. callout_handle->setArgument("lease6", lease);
  1030. // Pass the IA option to be sent in response
  1031. if (lease->type_ == Lease::TYPE_NA) {
  1032. callout_handle->setArgument("ia_na", ctx.ia_rsp_);
  1033. } else {
  1034. callout_handle->setArgument("ia_pd", ctx.ia_rsp_);
  1035. }
  1036. // Call all installed callouts
  1037. HooksManager::callCallouts(hook_point, *callout_handle);
  1038. // Callouts decided to skip the next processing step. The next
  1039. // processing step would actually renew the lease, so skip at this
  1040. // stage means "keep the old lease as it is".
  1041. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  1042. skip = true;
  1043. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  1044. DHCPSRV_HOOK_LEASE6_EXTEND_SKIP)
  1045. .arg(ctx.query_->getName());
  1046. }
  1047. /// @todo: Add support for DROP status
  1048. }
  1049. if (!skip) {
  1050. // If the lease we're renewing has expired, we need to reclaim this
  1051. // lease before we can renew it.
  1052. if (old_data->expired()) {
  1053. reclaimExpiredLease(old_data, ctx.callout_handle_);
  1054. } else if (!lease->hasIdenticalFqdn(*old_data)) {
  1055. // We're not reclaiming the lease but since the FQDN has changed
  1056. // we have to at least send NCR.
  1057. queueNCR(CHG_REMOVE, old_data);
  1058. }
  1059. // Now that the lease has been reclaimed, we can go ahead and update it
  1060. // in the lease database.
  1061. LeaseMgrFactory::instance().updateLease6(lease);
  1062. } else {
  1063. // Copy back the original date to the lease. For MySQL it doesn't make
  1064. // much sense, but for memfile, the Lease6Ptr points to the actual lease
  1065. // in memfile, so the actual update is performed when we manipulate
  1066. // fields of returned Lease6Ptr, the actual updateLease6() is no-op.
  1067. *lease = *old_data;
  1068. }
  1069. }
  1070. Lease6Collection
  1071. AllocEngine::updateLeaseData(ClientContext6& ctx, const Lease6Collection& leases) {
  1072. Lease6Collection updated_leases;
  1073. for (Lease6Collection::const_iterator lease_it = leases.begin();
  1074. lease_it != leases.end(); ++lease_it) {
  1075. Lease6Ptr lease(new Lease6(**lease_it));
  1076. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  1077. lease->fqdn_rev_ = ctx.rev_dns_update_;
  1078. lease->hostname_ = ctx.hostname_;
  1079. if (!ctx.fake_allocation_ &&
  1080. (conditionalExtendLifetime(*lease) ||
  1081. (lease->fqdn_fwd_ != (*lease_it)->fqdn_fwd_) ||
  1082. (lease->fqdn_rev_ != (*lease_it)->fqdn_rev_) ||
  1083. (lease->hostname_ != (*lease_it)->hostname_))) {
  1084. ctx.changed_leases_.push_back(*lease_it);
  1085. LeaseMgrFactory::instance().updateLease6(lease);
  1086. }
  1087. updated_leases.push_back(lease);
  1088. }
  1089. return (updated_leases);
  1090. }
  1091. void
  1092. AllocEngine::reclaimExpiredLeases6(const size_t max_leases, const uint16_t timeout,
  1093. const bool remove_lease,
  1094. const uint16_t max_unwarned_cycles) {
  1095. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1096. ALLOC_ENGINE_V6_LEASES_RECLAMATION_START)
  1097. .arg(max_leases)
  1098. .arg(timeout);
  1099. // Create stopwatch and automatically start it to measure the time
  1100. // taken by the routine.
  1101. util::Stopwatch stopwatch;
  1102. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1103. // This value indicates if we have been able to deal with all expired
  1104. // leases in this pass.
  1105. bool incomplete_reclamation = false;
  1106. Lease6Collection leases;
  1107. // The value of 0 has a special meaning - reclaim all.
  1108. if (max_leases > 0) {
  1109. // If the value is non-zero, the caller has limited the number of
  1110. // leases to reclaim. We obtain one lease more to see if there will
  1111. // be still leases left after this pass.
  1112. lease_mgr.getExpiredLeases6(leases, max_leases + 1);
  1113. // There are more leases expired leases than we will process in this
  1114. // pass, so we should mark it as an incomplete reclamation. We also
  1115. // remove this extra lease (which we don't want to process anyway)
  1116. // from the collection.
  1117. if (leases.size() > max_leases) {
  1118. leases.pop_back();
  1119. incomplete_reclamation = true;
  1120. }
  1121. } else {
  1122. // If there is no limitation on the number of leases to reclaim,
  1123. // we will try to process all. Hence, we don't mark it as incomplete
  1124. // reclamation just yet.
  1125. lease_mgr.getExpiredLeases6(leases, max_leases);
  1126. }
  1127. // Do not initialize the callout handle until we know if there are any
  1128. // lease6_expire callouts installed.
  1129. CalloutHandlePtr callout_handle;
  1130. if (!leases.empty() &&
  1131. HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease6_expire_)) {
  1132. callout_handle = HooksManager::createCalloutHandle();
  1133. }
  1134. size_t leases_processed = 0;
  1135. BOOST_FOREACH(Lease6Ptr lease, leases) {
  1136. try {
  1137. // Reclaim the lease.
  1138. reclaimExpiredLease(lease, remove_lease, callout_handle);
  1139. ++leases_processed;
  1140. } catch (const std::exception& ex) {
  1141. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_LEASE_RECLAMATION_FAILED)
  1142. .arg(lease->addr_.toText())
  1143. .arg(ex.what());
  1144. }
  1145. // Check if we have hit the timeout for running reclamation routine and
  1146. // return if we have. We're checking it here, because we always want to
  1147. // allow reclaiming at least one lease.
  1148. if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
  1149. // Timeout. This will likely mean that we haven't been able to process
  1150. // all leases we wanted to process. The reclamation pass will be
  1151. // probably marked as incomplete.
  1152. if (!incomplete_reclamation) {
  1153. if (leases_processed < leases.size()) {
  1154. incomplete_reclamation = true;
  1155. }
  1156. }
  1157. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1158. ALLOC_ENGINE_V6_LEASES_RECLAMATION_TIMEOUT)
  1159. .arg(timeout);
  1160. break;
  1161. }
  1162. }
  1163. // Stop measuring the time.
  1164. stopwatch.stop();
  1165. // Mark completion of the lease reclamation routine and present some stats.
  1166. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1167. ALLOC_ENGINE_V6_LEASES_RECLAMATION_COMPLETE)
  1168. .arg(leases_processed)
  1169. .arg(stopwatch.logFormatTotalDuration());
  1170. // Check if this was an incomplete reclamation and increase the number of
  1171. // consecutive incomplete reclamations.
  1172. if (incomplete_reclamation) {
  1173. ++incomplete_v6_reclamations_;
  1174. // If the number of incomplete reclamations is beyond the threshold, we
  1175. // need to issue a warning.
  1176. if ((max_unwarned_cycles > 0) &&
  1177. (incomplete_v6_reclamations_ > max_unwarned_cycles)) {
  1178. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V6_LEASES_RECLAMATION_SLOW)
  1179. .arg(max_unwarned_cycles);
  1180. // We issued a warning, so let's now reset the counter.
  1181. incomplete_v6_reclamations_ = 0;
  1182. }
  1183. } else {
  1184. // This was a complete reclamation, so let's reset the counter.
  1185. incomplete_v6_reclamations_ = 0;
  1186. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1187. ALLOC_ENGINE_V6_NO_MORE_EXPIRED_LEASES);
  1188. }
  1189. }
  1190. void
  1191. AllocEngine::deleteExpiredReclaimedLeases6(const uint32_t secs) {
  1192. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1193. ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE)
  1194. .arg(secs);
  1195. uint64_t deleted_leases = 0;
  1196. try {
  1197. // Try to delete leases from the lease database.
  1198. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1199. deleted_leases = lease_mgr.deleteExpiredReclaimedLeases6(secs);
  1200. } catch (const std::exception& ex) {
  1201. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE_FAILED)
  1202. .arg(ex.what());
  1203. }
  1204. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1205. ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE_COMPLETE)
  1206. .arg(deleted_leases);
  1207. }
  1208. void
  1209. AllocEngine::reclaimExpiredLeases4(const size_t max_leases, const uint16_t timeout,
  1210. const bool remove_lease,
  1211. const uint16_t max_unwarned_cycles) {
  1212. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1213. ALLOC_ENGINE_V4_LEASES_RECLAMATION_START)
  1214. .arg(max_leases)
  1215. .arg(timeout);
  1216. // Create stopwatch and automatically start it to measure the time
  1217. // taken by the routine.
  1218. util::Stopwatch stopwatch;
  1219. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1220. // This value indicates if we have been able to deal with all expired
  1221. // leases in this pass.
  1222. bool incomplete_reclamation = false;
  1223. Lease4Collection leases;
  1224. // The value of 0 has a special meaning - reclaim all.
  1225. if (max_leases > 0) {
  1226. // If the value is non-zero, the caller has limited the number of
  1227. // leases to reclaim. We obtain one lease more to see if there will
  1228. // be still leases left after this pass.
  1229. lease_mgr.getExpiredLeases4(leases, max_leases + 1);
  1230. // There are more leases expired leases than we will process in this
  1231. // pass, so we should mark it as an incomplete reclamation. We also
  1232. // remove this extra lease (which we don't want to process anyway)
  1233. // from the collection.
  1234. if (leases.size() > max_leases) {
  1235. leases.pop_back();
  1236. incomplete_reclamation = true;
  1237. }
  1238. } else {
  1239. // If there is no limitation on the number of leases to reclaim,
  1240. // we will try to process all. Hence, we don't mark it as incomplete
  1241. // reclamation just yet.
  1242. lease_mgr.getExpiredLeases4(leases, max_leases);
  1243. }
  1244. // Do not initialize the callout handle until we know if there are any
  1245. // lease4_expire callouts installed.
  1246. CalloutHandlePtr callout_handle;
  1247. if (!leases.empty() &&
  1248. HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease4_expire_)) {
  1249. callout_handle = HooksManager::createCalloutHandle();
  1250. }
  1251. size_t leases_processed = 0;
  1252. BOOST_FOREACH(Lease4Ptr lease, leases) {
  1253. try {
  1254. // Reclaim the lease.
  1255. reclaimExpiredLease(lease, remove_lease, callout_handle);
  1256. ++leases_processed;
  1257. } catch (const std::exception& ex) {
  1258. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V4_LEASE_RECLAMATION_FAILED)
  1259. .arg(lease->addr_.toText())
  1260. .arg(ex.what());
  1261. }
  1262. // Check if we have hit the timeout for running reclamation routine and
  1263. // return if we have. We're checking it here, because we always want to
  1264. // allow reclaiming at least one lease.
  1265. if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
  1266. // Timeout. This will likely mean that we haven't been able to process
  1267. // all leases we wanted to process. The reclamation pass will be
  1268. // probably marked as incomplete.
  1269. if (!incomplete_reclamation) {
  1270. if (leases_processed < leases.size()) {
  1271. incomplete_reclamation = true;
  1272. }
  1273. }
  1274. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1275. ALLOC_ENGINE_V4_LEASES_RECLAMATION_TIMEOUT)
  1276. .arg(timeout);
  1277. break;
  1278. }
  1279. }
  1280. // Stop measuring the time.
  1281. stopwatch.stop();
  1282. // Mark completion of the lease reclamation routine and present some stats.
  1283. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1284. ALLOC_ENGINE_V4_LEASES_RECLAMATION_COMPLETE)
  1285. .arg(leases_processed)
  1286. .arg(stopwatch.logFormatTotalDuration());
  1287. // Check if this was an incomplete reclamation and increase the number of
  1288. // consecutive incomplete reclamations.
  1289. if (incomplete_reclamation) {
  1290. ++incomplete_v4_reclamations_;
  1291. // If the number of incomplete reclamations is beyond the threshold, we
  1292. // need to issue a warning.
  1293. if ((max_unwarned_cycles > 0) &&
  1294. (incomplete_v4_reclamations_ > max_unwarned_cycles)) {
  1295. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V4_LEASES_RECLAMATION_SLOW)
  1296. .arg(max_unwarned_cycles);
  1297. // We issued a warning, so let's now reset the counter.
  1298. incomplete_v4_reclamations_ = 0;
  1299. }
  1300. } else {
  1301. // This was a complete reclamation, so let's reset the counter.
  1302. incomplete_v4_reclamations_ = 0;
  1303. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1304. ALLOC_ENGINE_V4_NO_MORE_EXPIRED_LEASES);
  1305. }
  1306. }
  1307. template<typename LeasePtrType>
  1308. void
  1309. AllocEngine::reclaimExpiredLease(const LeasePtrType& lease, const bool remove_lease,
  1310. const CalloutHandlePtr& callout_handle) {
  1311. reclaimExpiredLease(lease, remove_lease ? DB_RECLAIM_REMOVE : DB_RECLAIM_UPDATE,
  1312. callout_handle);
  1313. }
  1314. template<typename LeasePtrType>
  1315. void
  1316. AllocEngine::reclaimExpiredLease(const LeasePtrType& lease,
  1317. const CalloutHandlePtr& callout_handle) {
  1318. // This variant of the method is used by the code which allocates or
  1319. // renews leases. It may be the case that the lease has already been
  1320. // reclaimed, so there is nothing to do.
  1321. if (!lease->stateExpiredReclaimed()) {
  1322. reclaimExpiredLease(lease, DB_RECLAIM_LEAVE_UNCHANGED, callout_handle);
  1323. }
  1324. }
  1325. void
  1326. AllocEngine::reclaimExpiredLease(const Lease6Ptr& lease,
  1327. const DbReclaimMode& reclaim_mode,
  1328. const CalloutHandlePtr& callout_handle) {
  1329. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1330. ALLOC_ENGINE_V6_LEASE_RECLAIM)
  1331. .arg(Pkt6::makeLabel(lease->duid_, lease->hwaddr_))
  1332. .arg(lease->addr_.toText())
  1333. .arg(static_cast<int>(lease->prefixlen_));
  1334. // The skip flag indicates if the callouts have taken responsibility
  1335. // for reclaiming the lease. The callout will set this to true if
  1336. // it reclaims the lease itself. In this case the reclamation routine
  1337. // will not update DNS nor update the database.
  1338. bool skipped = false;
  1339. if (callout_handle) {
  1340. callout_handle->deleteAllArguments();
  1341. callout_handle->setArgument("lease6", lease);
  1342. callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
  1343. HooksManager::callCallouts(Hooks.hook_index_lease6_expire_,
  1344. *callout_handle);
  1345. skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
  1346. }
  1347. /// @todo: Maybe add support for DROP status?
  1348. /// Not sure if we need to support every possible status everywhere.
  1349. if (!skipped) {
  1350. // Generate removal name change request for D2, if required.
  1351. // This will return immediately if the DNS wasn't updated
  1352. // when the lease was created.
  1353. queueNCR(CHG_REMOVE, lease);
  1354. // Let's check if the lease that just expired is in DECLINED state.
  1355. // If it is, we need to perform a couple extra steps.
  1356. bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
  1357. if (lease->state_ == Lease::STATE_DECLINED) {
  1358. // Do extra steps required for declined lease reclamation:
  1359. // - call the recover hook
  1360. // - bump decline-related stats
  1361. // - log separate message
  1362. // There's no point in keeping a declined lease after its
  1363. // reclamation. A declined lease doesn't have any client
  1364. // identifying information anymore. So we'll flag it for
  1365. // removal unless the hook has set the skip flag.
  1366. remove_lease = reclaimDeclined(lease);
  1367. }
  1368. if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
  1369. // Reclaim the lease - depending on the configuration, set the
  1370. // expired-reclaimed state or simply remove it.
  1371. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1372. reclaimLeaseInDatabase<Lease6Ptr>(lease, remove_lease,
  1373. boost::bind(&LeaseMgr::updateLease6,
  1374. &lease_mgr, _1));
  1375. }
  1376. }
  1377. // Update statistics.
  1378. // Decrease number of assigned leases.
  1379. if (lease->type_ == Lease::TYPE_NA) {
  1380. // IA_NA
  1381. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1382. lease->subnet_id_,
  1383. "assigned-nas"),
  1384. int64_t(-1));
  1385. } else if (lease->type_ == Lease::TYPE_PD) {
  1386. // IA_PD
  1387. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1388. lease->subnet_id_,
  1389. "assigned-pds"),
  1390. int64_t(-1));
  1391. }
  1392. // Increase total number of reclaimed leases.
  1393. StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
  1394. // Increase number of reclaimed leases for a subnet.
  1395. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1396. lease->subnet_id_,
  1397. "reclaimed-leases"),
  1398. int64_t(1));
  1399. }
  1400. void
  1401. AllocEngine::reclaimExpiredLease(const Lease4Ptr& lease,
  1402. const DbReclaimMode& reclaim_mode,
  1403. const CalloutHandlePtr& callout_handle) {
  1404. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1405. ALLOC_ENGINE_V4_LEASE_RECLAIM)
  1406. .arg(Pkt4::makeLabel(lease->hwaddr_, lease->client_id_))
  1407. .arg(lease->addr_.toText());
  1408. // The skip flag indicates if the callouts have taken responsibility
  1409. // for reclaiming the lease. The callout will set this to true if
  1410. // it reclaims the lease itself. In this case the reclamation routine
  1411. // will not update DNS nor update the database.
  1412. bool skipped = false;
  1413. if (callout_handle) {
  1414. callout_handle->deleteAllArguments();
  1415. callout_handle->setArgument("lease4", lease);
  1416. callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
  1417. HooksManager::callCallouts(Hooks.hook_index_lease4_expire_,
  1418. *callout_handle);
  1419. skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
  1420. }
  1421. /// @todo: Maybe add support for DROP status?
  1422. /// Not sure if we need to support every possible status everywhere.
  1423. if (!skipped) {
  1424. // Generate removal name change request for D2, if required.
  1425. // This will return immediatelly if the DNS wasn't updated
  1426. // when the lease was created.
  1427. queueNCR(CHG_REMOVE, lease);
  1428. // Let's check if the lease that just expired is in DECLINED state.
  1429. // If it is, we need to perform a couple extra steps.
  1430. bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
  1431. if (lease->state_ == Lease::STATE_DECLINED) {
  1432. // Do extra steps required for declined lease reclamation:
  1433. // - call the recover hook
  1434. // - bump decline-related stats
  1435. // - log separate message
  1436. // There's no point in keeping a declined lease after its
  1437. // reclamation. A declined lease doesn't have any client
  1438. // identifying information anymore. So we'll flag it for
  1439. // removal unless the hook has set the skip flag.
  1440. remove_lease = reclaimDeclined(lease);
  1441. }
  1442. if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
  1443. // Reclaim the lease - depending on the configuration, set the
  1444. // expired-reclaimed state or simply remove it.
  1445. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1446. reclaimLeaseInDatabase<Lease4Ptr>(lease, remove_lease,
  1447. boost::bind(&LeaseMgr::updateLease4,
  1448. &lease_mgr, _1));
  1449. }
  1450. }
  1451. // Update statistics.
  1452. // Decrease number of assigned addresses.
  1453. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1454. lease->subnet_id_,
  1455. "assigned-addresses"),
  1456. int64_t(-1));
  1457. // Increase total number of reclaimed leases.
  1458. StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
  1459. // Increase number of reclaimed leases for a subnet.
  1460. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1461. lease->subnet_id_,
  1462. "reclaimed-leases"),
  1463. int64_t(1));
  1464. }
  1465. void
  1466. AllocEngine::deleteExpiredReclaimedLeases4(const uint32_t secs) {
  1467. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1468. ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE)
  1469. .arg(secs);
  1470. uint64_t deleted_leases = 0;
  1471. try {
  1472. // Try to delete leases from the lease database.
  1473. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1474. deleted_leases = lease_mgr.deleteExpiredReclaimedLeases4(secs);
  1475. } catch (const std::exception& ex) {
  1476. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE_FAILED)
  1477. .arg(ex.what());
  1478. }
  1479. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1480. ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE_COMPLETE)
  1481. .arg(deleted_leases);
  1482. }
  1483. bool
  1484. AllocEngine::reclaimDeclined(const Lease4Ptr& lease) {
  1485. if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
  1486. return (true);
  1487. }
  1488. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease4_recover_)) {
  1489. // Let's use a static callout handle. It will be initialized the first
  1490. // time lease4_recover is called and will keep to that value.
  1491. static CalloutHandlePtr callout_handle;
  1492. if (!callout_handle) {
  1493. callout_handle = HooksManager::createCalloutHandle();
  1494. }
  1495. // Delete all previous arguments
  1496. callout_handle->deleteAllArguments();
  1497. // Pass necessary arguments
  1498. callout_handle->setArgument("lease4", lease);
  1499. // Call the callouts
  1500. HooksManager::callCallouts(Hooks.hook_index_lease4_recover_, *callout_handle);
  1501. // Callouts decided to skip the action. This means that the lease is not
  1502. // assigned, so the client will get NoAddrAvail as a result. The lease
  1503. // won't be inserted into the database.
  1504. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  1505. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_RECOVER_SKIP)
  1506. .arg(lease->addr_.toText());
  1507. return (false);
  1508. }
  1509. }
  1510. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V4_DECLINED_RECOVERED)
  1511. .arg(lease->addr_.toText())
  1512. .arg(lease->valid_lft_);
  1513. StatsMgr& stats_mgr = StatsMgr::instance();
  1514. // Decrease subnet specific counter for currently declined addresses
  1515. stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
  1516. "declined-addresses"), static_cast<int64_t>(-1));
  1517. // Decrease global counter for declined addresses
  1518. stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
  1519. stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
  1520. stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
  1521. "reclaimed-declined-addresses"), static_cast<int64_t>(1));
  1522. // Note that we do not touch assigned-addresses counters. Those are
  1523. // modified in whatever code calls this method.
  1524. return (true);
  1525. }
  1526. bool
  1527. AllocEngine::reclaimDeclined(const Lease6Ptr& lease) {
  1528. if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
  1529. return (true);
  1530. }
  1531. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease6_recover_)) {
  1532. // Let's use a static callout handle. It will be initialized the first
  1533. // time lease6_recover is called and will keep to that value.
  1534. static CalloutHandlePtr callout_handle;
  1535. if (!callout_handle) {
  1536. callout_handle = HooksManager::createCalloutHandle();
  1537. }
  1538. // Delete all previous arguments
  1539. callout_handle->deleteAllArguments();
  1540. // Pass necessary arguments
  1541. callout_handle->setArgument("lease6", lease);
  1542. // Call the callouts
  1543. HooksManager::callCallouts(Hooks.hook_index_lease6_recover_, *callout_handle);
  1544. // Callouts decided to skip the action. This means that the lease is not
  1545. // assigned, so the client will get NoAddrAvail as a result. The lease
  1546. // won't be inserted into the database.
  1547. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  1548. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_RECOVER_SKIP)
  1549. .arg(lease->addr_.toText());
  1550. return (false);
  1551. }
  1552. }
  1553. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_DECLINED_RECOVERED)
  1554. .arg(lease->addr_.toText())
  1555. .arg(lease->valid_lft_);
  1556. StatsMgr& stats_mgr = StatsMgr::instance();
  1557. // Decrease subnet specific counter for currently declined addresses
  1558. stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
  1559. "declined-addresses"), static_cast<int64_t>(-1));
  1560. // Decrease global counter for declined addresses
  1561. stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
  1562. stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
  1563. stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
  1564. "reclaimed-declined-addresses"), static_cast<int64_t>(1));
  1565. // Note that we do not touch assigned-addresses counters. Those are
  1566. // modified in whatever code calls this method.
  1567. return (true);
  1568. }
  1569. template<typename LeasePtrType>
  1570. void AllocEngine::reclaimLeaseInDatabase(const LeasePtrType& lease,
  1571. const bool remove_lease,
  1572. const boost::function<void (const LeasePtrType&)>&
  1573. lease_update_fun) const {
  1574. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1575. // Reclaim the lease - depending on the configuration, set the
  1576. // expired-reclaimed state or simply remove it.
  1577. if (remove_lease) {
  1578. lease_mgr.deleteLease(lease->addr_);
  1579. } else if (!lease_update_fun.empty()) {
  1580. // Clear FQDN information as we have already sent the
  1581. // name change request to remove the DNS record.
  1582. lease->hostname_.clear();
  1583. lease->fqdn_fwd_ = false;
  1584. lease->fqdn_rev_ = false;
  1585. lease->state_ = Lease::STATE_EXPIRED_RECLAIMED;
  1586. lease_update_fun(lease);
  1587. } else {
  1588. return;
  1589. }
  1590. // Lease has been reclaimed.
  1591. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1592. ALLOC_ENGINE_LEASE_RECLAIMED)
  1593. .arg(lease->addr_.toText());
  1594. }
  1595. } // end of isc::dhcp namespace
  1596. } // end of isc namespace
  1597. // ##########################################################################
  1598. // # DHCPv4 lease allocation code starts here.
  1599. // ##########################################################################
  1600. namespace {
  1601. /// @brief Check if the specific address is reserved for another client.
  1602. ///
  1603. /// This function uses the HW address from the context to check if the
  1604. /// requested address (specified as first parameter) is reserved for
  1605. /// another client, i.e. client using a different HW address.
  1606. ///
  1607. /// @param address An address for which the function should check if
  1608. /// there is a reservation for the different client.
  1609. /// @param ctx Client context holding the data extracted from the
  1610. /// client's message.
  1611. ///
  1612. /// @return true if the address is reserved for another client.
  1613. bool
  1614. addressReserved(const IOAddress& address, const AllocEngine::ClientContext4& ctx) {
  1615. ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(), address);
  1616. HWAddrPtr host_hwaddr;
  1617. if (host) {
  1618. host_hwaddr = host->getHWAddress();
  1619. if (ctx.hwaddr_ && host_hwaddr) {
  1620. /// @todo Use the equality operators for HWAddr class.
  1621. /// Currently, this is impossible because the HostMgr uses the
  1622. /// HTYPE_ETHER type, whereas the unit tests may use other types
  1623. /// which HostMgr doesn't support yet.
  1624. return (host_hwaddr->hwaddr_ != ctx.hwaddr_->hwaddr_);
  1625. } else {
  1626. return (false);
  1627. }
  1628. }
  1629. return (false);
  1630. }
  1631. /// @brief Check if the context contains the reservation for the
  1632. /// IPv4 address.
  1633. ///
  1634. /// This convenience function checks if the context contains the reservation
  1635. /// for the IPv4 address. Note that some reservations may not assign a
  1636. /// static IPv4 address to the clients, but may rather reserve a hostname.
  1637. /// Allocation engine should check if the existing reservation is made
  1638. /// for the IPv4 address and if it is not, allocate the address from the
  1639. /// dynamic pool. The allocation engine uses this function to check if
  1640. /// the reservation is made for the IPv4 address.
  1641. ///
  1642. /// @param ctx Client context holding the data extracted from the
  1643. /// client's message.
  1644. ///
  1645. /// @return true if the context contains the reservation for the IPv4 address.
  1646. bool
  1647. hasAddressReservation(const AllocEngine::ClientContext4& ctx) {
  1648. return (ctx.host_ && !ctx.host_->getIPv4Reservation().isV4Zero());
  1649. }
  1650. /// @brief Finds existing lease in the database.
  1651. ///
  1652. /// This function searches for the lease in the database which belongs to the
  1653. /// client requesting allocation. If the client has supplied the client
  1654. /// identifier this identifier is used to look up the lease. If the lease is
  1655. /// not found using the client identifier, an additional lookup is performed
  1656. /// using the HW address, if supplied. If the lease is found using the HW
  1657. /// address, the function also checks if the lease belongs to the client, i.e.
  1658. /// there is no conflict between the client identifiers.
  1659. ///
  1660. /// @param ctx Context holding data extracted from the client's message,
  1661. /// including the HW address and client identifier.
  1662. /// @param [out] client_lease A pointer to the lease returned by this function
  1663. /// or null value if no has been lease found.
  1664. void findClientLease(const AllocEngine::ClientContext4& ctx, Lease4Ptr& client_lease) {
  1665. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1666. // If client identifier has been supplied, use it to lookup the lease. This
  1667. // search will return no lease if the client doesn't have any lease in the
  1668. // database or if the client didn't use client identifier to allocate the
  1669. // existing lease (this include cases when the server was explicitly
  1670. // configured to ignore client identifier).
  1671. if (ctx.clientid_) {
  1672. client_lease = lease_mgr.getLease4(*ctx.clientid_, ctx.subnet_->getID());
  1673. }
  1674. // If no lease found using the client identifier, try the lookup using
  1675. // the HW address.
  1676. if (!client_lease && ctx.hwaddr_) {
  1677. client_lease = lease_mgr.getLease4(*ctx.hwaddr_, ctx.subnet_->getID());
  1678. // This lookup may return the lease which has conflicting client
  1679. // identifier and thus is considered to belong to someone else.
  1680. // If this is the case, we need to toss the result and force the
  1681. // Allocation Engine to allocate another lease.
  1682. if (client_lease && !client_lease->belongsToClient(ctx.hwaddr_, ctx.clientid_)) {
  1683. client_lease.reset();
  1684. }
  1685. }
  1686. }
  1687. } // end of anonymous namespace
  1688. namespace isc {
  1689. namespace dhcp {
  1690. AllocEngine::ClientContext4::ClientContext4()
  1691. : subnet_(), clientid_(), hwaddr_(),
  1692. requested_address_(IOAddress::IPV4_ZERO_ADDRESS()),
  1693. fwd_dns_update_(false), rev_dns_update_(false),
  1694. hostname_(""), callout_handle_(), fake_allocation_(false),
  1695. old_lease_(), host_(), conflicting_lease_(), query_(),
  1696. host_identifiers_() {
  1697. }
  1698. AllocEngine::ClientContext4::ClientContext4(const Subnet4Ptr& subnet,
  1699. const ClientIdPtr& clientid,
  1700. const HWAddrPtr& hwaddr,
  1701. const asiolink::IOAddress& requested_addr,
  1702. const bool fwd_dns_update,
  1703. const bool rev_dns_update,
  1704. const std::string& hostname,
  1705. const bool fake_allocation)
  1706. : subnet_(subnet), clientid_(clientid), hwaddr_(hwaddr),
  1707. requested_address_(requested_addr),
  1708. fwd_dns_update_(fwd_dns_update), rev_dns_update_(rev_dns_update),
  1709. hostname_(hostname), callout_handle_(),
  1710. fake_allocation_(fake_allocation), old_lease_(), host_(),
  1711. host_identifiers_() {
  1712. // Initialize host identifiers.
  1713. if (hwaddr) {
  1714. addHostIdentifier(Host::IDENT_HWADDR, hwaddr->hwaddr_);
  1715. }
  1716. }
  1717. Lease4Ptr
  1718. AllocEngine::allocateLease4(ClientContext4& ctx) {
  1719. // The NULL pointer indicates that the old lease didn't exist. It may
  1720. // be later set to non NULL value if existing lease is found in the
  1721. // database.
  1722. ctx.old_lease_.reset();
  1723. Lease4Ptr new_lease;
  1724. try {
  1725. if (!ctx.subnet_) {
  1726. isc_throw(BadValue, "Can't allocate IPv4 address without subnet");
  1727. }
  1728. if (!ctx.hwaddr_) {
  1729. isc_throw(BadValue, "HWAddr must be defined");
  1730. }
  1731. new_lease = ctx.fake_allocation_ ? discoverLease4(ctx) : requestLease4(ctx);
  1732. } catch (const isc::Exception& e) {
  1733. // Some other error, return an empty lease.
  1734. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V4_ALLOC_ERROR)
  1735. .arg(ctx.query_->getLabel())
  1736. .arg(e.what());
  1737. }
  1738. return (new_lease);
  1739. }
  1740. void
  1741. AllocEngine::findReservation(ClientContext4& ctx) {
  1742. findReservationInternal(ctx, boost::bind(&HostMgr::get4,
  1743. &HostMgr::instance(),
  1744. _1, _2, _3, _4));
  1745. }
  1746. Lease4Ptr
  1747. AllocEngine::discoverLease4(AllocEngine::ClientContext4& ctx) {
  1748. // Find an existing lease for this client. This function will return true
  1749. // if there is a conflict with existing lease and the allocation should
  1750. // not be continued.
  1751. Lease4Ptr client_lease;
  1752. findClientLease(ctx, client_lease);
  1753. // new_lease will hold the pointer to the lease that we will offer to the
  1754. // caller.
  1755. Lease4Ptr new_lease;
  1756. // Check if there is a reservation for the client. If there is, we want to
  1757. // assign the reserved address, rather than any other one.
  1758. if (hasAddressReservation(ctx)) {
  1759. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1760. ALLOC_ENGINE_V4_DISCOVER_HR)
  1761. .arg(ctx.query_->getLabel())
  1762. .arg(ctx.host_->getIPv4Reservation().toText());
  1763. // If the client doesn't have a lease or the leased address is different
  1764. // than the reserved one then let's try to allocate the reserved address.
  1765. // Otherwise the address that the client has is the one for which it
  1766. // has a reservation, so just renew it.
  1767. if (!client_lease || (client_lease->addr_ != ctx.host_->getIPv4Reservation())) {
  1768. // The call below will return a pointer to the lease for the address
  1769. // reserved to this client, if the lease is available, i.e. is not
  1770. // currently assigned to any other client.
  1771. // Note that we don't remove the existing client's lease at this point
  1772. // because this is not a real allocation, we just offer what we can
  1773. // allocate in the DHCPREQUEST time.
  1774. new_lease = allocateOrReuseLease4(ctx.host_->getIPv4Reservation(), ctx);
  1775. if (!new_lease) {
  1776. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V4_DISCOVER_ADDRESS_CONFLICT)
  1777. .arg(ctx.query_->getLabel())
  1778. .arg(ctx.host_->getIPv4Reservation().toText())
  1779. .arg(ctx.conflicting_lease_ ? ctx.conflicting_lease_->toText() :
  1780. "(no lease info)");
  1781. }
  1782. } else {
  1783. new_lease = renewLease4(client_lease, ctx);
  1784. }
  1785. }
  1786. // Client does not have a reservation or the allocation of the reserved
  1787. // address has failed, probably because the reserved address is in use
  1788. // by another client. If the client has a lease, we will check if we can
  1789. // offer this lease to the client. The lease can't be offered in the
  1790. // situation when it is reserved for another client or when the address
  1791. // is not in the dynamic pool. The former may be the result of adding the
  1792. // new reservation for the address used by this client. The latter may
  1793. // be due to the client using the reserved out-of-the pool address, for
  1794. // which the reservation has just been removed.
  1795. if (!new_lease && client_lease &&
  1796. ctx.subnet_->inPool(Lease::TYPE_V4, client_lease->addr_) &&
  1797. !addressReserved(client_lease->addr_, ctx)) {
  1798. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1799. ALLOC_ENGINE_V4_OFFER_EXISTING_LEASE)
  1800. .arg(ctx.query_->getLabel());
  1801. new_lease = renewLease4(client_lease, ctx);
  1802. }
  1803. // The client doesn't have any lease or the lease can't be offered
  1804. // because it is either reserved for some other client or the
  1805. // address is not in the dynamic pool.
  1806. // Let's use the client's hint (requested IP address), if the client
  1807. // has provided it, and try to offer it. This address must not be
  1808. // reserved for another client, and must be in the range of the
  1809. // dynamic pool.
  1810. if (!new_lease && !ctx.requested_address_.isV4Zero() &&
  1811. ctx.subnet_->inPool(Lease::TYPE_V4, ctx.requested_address_) &&
  1812. !addressReserved(ctx.requested_address_, ctx)) {
  1813. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1814. ALLOC_ENGINE_V4_OFFER_REQUESTED_LEASE)
  1815. .arg(ctx.requested_address_.toText())
  1816. .arg(ctx.query_->getLabel());
  1817. new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx);
  1818. }
  1819. // The allocation engine failed to allocate all of the candidate
  1820. // addresses. We will now use the allocator to pick the address
  1821. // from the dynamic pool.
  1822. if (!new_lease) {
  1823. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1824. ALLOC_ENGINE_V4_OFFER_NEW_LEASE)
  1825. .arg(ctx.query_->getLabel());
  1826. new_lease = allocateUnreservedLease4(ctx);
  1827. }
  1828. // Some of the methods like reuseExpiredLease4 may set the old lease to point
  1829. // to the lease which they remove/override. If it is not set, but we have
  1830. // found that the client has the lease the client's lease is the one
  1831. // to return as an old lease.
  1832. if (!ctx.old_lease_ && client_lease) {
  1833. ctx.old_lease_ = client_lease;
  1834. }
  1835. return (new_lease);
  1836. }
  1837. Lease4Ptr
  1838. AllocEngine::requestLease4(AllocEngine::ClientContext4& ctx) {
  1839. // Find an existing lease for this client. This function will return true
  1840. // if there is a conflict with existing lease and the allocation should
  1841. // not be continued.
  1842. Lease4Ptr client_lease;
  1843. findClientLease(ctx, client_lease);
  1844. // Obtain the sole instance of the LeaseMgr.
  1845. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1846. // When the client sends the DHCPREQUEST, it should always specify the
  1847. // address which it is requesting or renewing. That is, the client should
  1848. // either use the requested IP address option or set the ciaddr. However,
  1849. // we try to be liberal and allow the clients to not specify an address
  1850. // in which case the allocation engine will pick a suitable address
  1851. // for the client.
  1852. if (!ctx.requested_address_.isV4Zero()) {
  1853. // If the client has specified an address, make sure this address
  1854. // is not reserved for another client. If it is, stop here because
  1855. // we can't allocate this address.
  1856. if (addressReserved(ctx.requested_address_, ctx)) {
  1857. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1858. ALLOC_ENGINE_V4_REQUEST_ADDRESS_RESERVED)
  1859. .arg(ctx.query_->getLabel())
  1860. .arg(ctx.requested_address_.toText());
  1861. return (Lease4Ptr());
  1862. }
  1863. } else if (hasAddressReservation(ctx)) {
  1864. // The client hasn't specified an address to allocate, so the
  1865. // allocation engine needs to find an appropriate address.
  1866. // If there is a reservation for the client, let's try to
  1867. // allocate the reserved address.
  1868. ctx.requested_address_ = ctx.host_->getIPv4Reservation();
  1869. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1870. ALLOC_ENGINE_V4_REQUEST_USE_HR)
  1871. .arg(ctx.query_->getLabel())
  1872. .arg(ctx.requested_address_.toText());
  1873. }
  1874. if (!ctx.requested_address_.isV4Zero()) {
  1875. // There is a specific address to be allocated. Let's find out if
  1876. // the address is in use.
  1877. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(ctx.requested_address_);
  1878. // If the address is in use (allocated and not expired), we check
  1879. // if the address is in use by our client or another client.
  1880. // If it is in use by another client, the address can't be
  1881. // allocated.
  1882. if (existing && !existing->expired() &&
  1883. !existing->belongsToClient(ctx.hwaddr_, ctx.clientid_)) {
  1884. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1885. ALLOC_ENGINE_V4_REQUEST_IN_USE)
  1886. .arg(ctx.query_->getLabel())
  1887. .arg(ctx.requested_address_.toText());
  1888. return (Lease4Ptr());
  1889. }
  1890. // If the client has a reservation but it is requesting a different
  1891. // address it is possible that the client was offered this different
  1892. // address because the reserved address is in use. We will have to
  1893. // check if the address is in use.
  1894. if (hasAddressReservation(ctx) &&
  1895. (ctx.host_->getIPv4Reservation() != ctx.requested_address_)) {
  1896. existing = LeaseMgrFactory::instance().getLease4(ctx.host_->getIPv4Reservation());
  1897. // If the reserved address is not in use, i.e. the lease doesn't
  1898. // exist or is expired, and the client is requesting a different
  1899. // address, return NULL. The client should go back to the
  1900. // DHCPDISCOVER and the reserved address will be offered.
  1901. if (!existing || existing->expired()) {
  1902. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1903. ALLOC_ENGINE_V4_REQUEST_INVALID)
  1904. .arg(ctx.query_->getLabel())
  1905. .arg(ctx.host_->getIPv4Reservation().toText())
  1906. .arg(ctx.requested_address_.toText());
  1907. return (Lease4Ptr());
  1908. }
  1909. }
  1910. // The use of the out-of-pool addresses is only allowed when the requested
  1911. // address is reserved for the client. If the address is not reserved one
  1912. // and it doesn't belong to the dynamic pool, do not allocate it.
  1913. if ((!hasAddressReservation(ctx) ||
  1914. (ctx.host_->getIPv4Reservation() != ctx.requested_address_)) &&
  1915. !ctx.subnet_->inPool(Lease4::TYPE_V4, ctx.requested_address_)) {
  1916. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1917. ALLOC_ENGINE_V4_REQUEST_OUT_OF_POOL)
  1918. .arg(ctx.query_->getLabel())
  1919. .arg(ctx.requested_address_);
  1920. return (Lease4Ptr());
  1921. }
  1922. }
  1923. // We have gone through all the checks, so we can now allocate the address
  1924. // for the client.
  1925. // If the client is requesting an address which is assigned to the client
  1926. // let's just renew this address. Also, renew this address if the client
  1927. // doesn't request any specific address.
  1928. if (client_lease) {
  1929. if ((client_lease->addr_ == ctx.requested_address_) ||
  1930. ctx.requested_address_.isV4Zero()) {
  1931. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1932. ALLOC_ENGINE_V4_REQUEST_EXTEND_LEASE)
  1933. .arg(ctx.query_->getLabel())
  1934. .arg(ctx.requested_address_);
  1935. return (renewLease4(client_lease, ctx));
  1936. }
  1937. }
  1938. // new_lease will hold the pointer to the allocated lease if we allocate
  1939. // successfully.
  1940. Lease4Ptr new_lease;
  1941. // The client doesn't have the lease or it is requesting an address
  1942. // which it doesn't have. Let's try to allocate the requested address.
  1943. if (!ctx.requested_address_.isV4Zero()) {
  1944. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1945. ALLOC_ENGINE_V4_REQUEST_ALLOC_REQUESTED)
  1946. .arg(ctx.query_->getLabel())
  1947. .arg(ctx.requested_address_.toText());
  1948. // The call below will return a pointer to the lease allocated
  1949. // for the client if there is no lease for the requested address,
  1950. // or the existing lease has expired. If the allocation fails,
  1951. // e.g. because the lease is in use, we will return NULL to
  1952. // indicate that we were unable to allocate the lease.
  1953. new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx);
  1954. } else {
  1955. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1956. ALLOC_ENGINE_V4_REQUEST_PICK_ADDRESS)
  1957. .arg(ctx.query_->getLabel());
  1958. // We will only get here if the client didn't specify which
  1959. // address it wanted to be allocated. The allocation engine will
  1960. // to pick the address from the dynamic pool.
  1961. new_lease = allocateUnreservedLease4(ctx);
  1962. }
  1963. // If we allocated the lease for the client, but the client already had a
  1964. // lease, we will need to return the pointer to the previous lease and
  1965. // the previous lease needs to be removed from the lease database.
  1966. if (new_lease && client_lease) {
  1967. ctx.old_lease_ = Lease4Ptr(new Lease4(*client_lease));
  1968. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1969. ALLOC_ENGINE_V4_REQUEST_REMOVE_LEASE)
  1970. .arg(ctx.query_->getLabel())
  1971. .arg(client_lease->addr_.toText());
  1972. lease_mgr.deleteLease(client_lease->addr_);
  1973. // Need to decrease statistic for assigned addresses.
  1974. StatsMgr::instance().addValue(
  1975. StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-addresses"),
  1976. static_cast<int64_t>(-1));
  1977. }
  1978. // Return the allocated lease or NULL pointer if allocation was
  1979. // unsuccessful.
  1980. return (new_lease);
  1981. }
  1982. Lease4Ptr
  1983. AllocEngine::createLease4(const ClientContext4& ctx, const IOAddress& addr) {
  1984. if (!ctx.hwaddr_) {
  1985. isc_throw(BadValue, "Can't create a lease with NULL HW address");
  1986. }
  1987. if (!ctx.subnet_) {
  1988. isc_throw(BadValue, "Can't create a lease without a subnet");
  1989. }
  1990. time_t now = time(NULL);
  1991. // @todo: remove this kludge after ticket #2590 is implemented
  1992. std::vector<uint8_t> local_copy;
  1993. if (ctx.clientid_) {
  1994. local_copy = ctx.clientid_->getDuid();
  1995. }
  1996. const uint8_t* local_copy0 = local_copy.empty() ? 0 : &local_copy[0];
  1997. Lease4Ptr lease(new Lease4(addr, ctx.hwaddr_, local_copy0, local_copy.size(),
  1998. ctx.subnet_->getValid(), ctx.subnet_->getT1(),
  1999. ctx.subnet_->getT2(),
  2000. now, ctx.subnet_->getID()));
  2001. // Set FQDN specific lease parameters.
  2002. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  2003. lease->fqdn_rev_ = ctx.rev_dns_update_;
  2004. lease->hostname_ = ctx.hostname_;
  2005. // Let's execute all callouts registered for lease4_select
  2006. if (ctx.callout_handle_ &&
  2007. HooksManager::getHooksManager().calloutsPresent(hook_index_lease4_select_)) {
  2008. // Delete all previous arguments
  2009. ctx.callout_handle_->deleteAllArguments();
  2010. // Pass necessary arguments
  2011. // Subnet from which we do the allocation (That's as far as we can go
  2012. // with using SubnetPtr to point to Subnet4 object. Users should not
  2013. // be confused with dynamic_pointer_casts. They should get a concrete
  2014. // pointer (Subnet4Ptr) pointing to a Subnet4 object.
  2015. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  2016. ctx.callout_handle_->setArgument("subnet4", subnet4);
  2017. // Is this solicit (fake = true) or request (fake = false)
  2018. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  2019. // Pass the intended lease as well
  2020. ctx.callout_handle_->setArgument("lease4", lease);
  2021. // This is the first callout, so no need to clear any arguments
  2022. HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
  2023. // Callouts decided to skip the action. This means that the lease is not
  2024. // assigned, so the client will get NoAddrAvail as a result. The lease
  2025. // won't be inserted into the database.
  2026. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  2027. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  2028. return (Lease4Ptr());
  2029. }
  2030. // Let's use whatever callout returned. Hopefully it is the same lease
  2031. // we handled to it.
  2032. ctx.callout_handle_->getArgument("lease4", lease);
  2033. }
  2034. if (!ctx.fake_allocation_) {
  2035. // That is a real (REQUEST) allocation
  2036. bool status = LeaseMgrFactory::instance().addLease(lease);
  2037. if (status) {
  2038. // The lease insertion succeeded, let's bump up the statistic.
  2039. StatsMgr::instance().addValue(
  2040. StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-addresses"),
  2041. static_cast<int64_t>(1));
  2042. return (lease);
  2043. } else {
  2044. // One of many failures with LeaseMgr (e.g. lost connection to the
  2045. // database, database failed etc.). One notable case for that
  2046. // is that we are working in multi-process mode and we lost a race
  2047. // (some other process got that address first)
  2048. return (Lease4Ptr());
  2049. }
  2050. } else {
  2051. // That is only fake (DISCOVER) allocation
  2052. // It is for OFFER only. We should not insert the lease into LeaseMgr,
  2053. // but rather check that we could have inserted it.
  2054. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(addr);
  2055. if (!existing) {
  2056. return (lease);
  2057. } else {
  2058. return (Lease4Ptr());
  2059. }
  2060. }
  2061. }
  2062. Lease4Ptr
  2063. AllocEngine::renewLease4(const Lease4Ptr& lease,
  2064. AllocEngine::ClientContext4& ctx) {
  2065. if (!lease) {
  2066. isc_throw(BadValue, "null lease specified for renewLease4");
  2067. }
  2068. // Let's keep the old data. This is essential if we are using memfile
  2069. // (the lease returned points directly to the lease4 object in the database)
  2070. // We'll need it if we want to skip update (i.e. roll back renewal)
  2071. /// @todo: remove this once #3083 is implemented
  2072. Lease4 old_values = *lease;
  2073. ctx.old_lease_.reset(new Lease4(old_values));
  2074. // Update the lease with the information from the context.
  2075. updateLease4Information(lease, ctx);
  2076. if (!ctx.fake_allocation_) {
  2077. // If the lease is expired we have to reclaim it before
  2078. // re-assigning it to the client. The lease reclamation
  2079. // involves execution of hooks and DNS update.
  2080. if (ctx.old_lease_->expired()) {
  2081. reclaimExpiredLease(ctx.old_lease_, ctx.callout_handle_);
  2082. lease->state_ = Lease::STATE_DEFAULT;
  2083. } else if (!lease->hasIdenticalFqdn(*ctx.old_lease_)) {
  2084. // The lease is not expired but the FQDN information has
  2085. // changed. So, we have to remove the previous DNS entry.
  2086. queueNCR(CHG_REMOVE, ctx.old_lease_);
  2087. }
  2088. }
  2089. bool skip = false;
  2090. // Execute all callouts registered for lease4_renew.
  2091. if (HooksManager::getHooksManager().
  2092. calloutsPresent(Hooks.hook_index_lease4_renew_)) {
  2093. // Delete all previous arguments
  2094. ctx.callout_handle_->deleteAllArguments();
  2095. // Subnet from which we do the allocation. Convert the general subnet
  2096. // pointer to a pointer to a Subnet4. Note that because we are using
  2097. // boost smart pointers here, we need to do the cast using the boost
  2098. // version of dynamic_pointer_cast.
  2099. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  2100. // Pass the parameters
  2101. ctx.callout_handle_->setArgument("subnet4", subnet4);
  2102. ctx.callout_handle_->setArgument("clientid", ctx.clientid_);
  2103. ctx.callout_handle_->setArgument("hwaddr", ctx.hwaddr_);
  2104. // Pass the lease to be updated
  2105. ctx.callout_handle_->setArgument("lease4", lease);
  2106. // Call all installed callouts
  2107. HooksManager::callCallouts(Hooks.hook_index_lease4_renew_,
  2108. *ctx.callout_handle_);
  2109. // Callouts decided to skip the next processing step. The next
  2110. // processing step would actually renew the lease, so skip at this
  2111. // stage means "keep the old lease as it is".
  2112. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  2113. skip = true;
  2114. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  2115. DHCPSRV_HOOK_LEASE4_RENEW_SKIP);
  2116. }
  2117. /// @todo: Add support for DROP status
  2118. }
  2119. if (!ctx.fake_allocation_ && !skip) {
  2120. // for REQUEST we do update the lease
  2121. LeaseMgrFactory::instance().updateLease4(lease);
  2122. }
  2123. if (skip) {
  2124. // Rollback changes (really useful only for memfile)
  2125. /// @todo: remove this once #3083 is implemented
  2126. *lease = old_values;
  2127. }
  2128. return (lease);
  2129. }
  2130. Lease4Ptr
  2131. AllocEngine::reuseExpiredLease4(Lease4Ptr& expired,
  2132. AllocEngine::ClientContext4& ctx) {
  2133. if (!expired) {
  2134. isc_throw(BadValue, "null lease specified for reuseExpiredLease");
  2135. }
  2136. if (!ctx.subnet_) {
  2137. isc_throw(BadValue, "null subnet specified for the reuseExpiredLease");
  2138. }
  2139. if (!ctx.fake_allocation_) {
  2140. // The expired lease needs to be reclaimed before it can be reused.
  2141. // This includes declined leases for which probation period has
  2142. // elapsed.
  2143. reclaimExpiredLease(expired, ctx.callout_handle_);
  2144. expired->state_ = Lease::STATE_DEFAULT;
  2145. }
  2146. updateLease4Information(expired, ctx);
  2147. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA,
  2148. ALLOC_ENGINE_V4_REUSE_EXPIRED_LEASE_DATA)
  2149. .arg(ctx.query_->getLabel())
  2150. .arg(expired->toText());
  2151. // Let's execute all callouts registered for lease4_select
  2152. if (ctx.callout_handle_ && HooksManager::getHooksManager()
  2153. .calloutsPresent(hook_index_lease4_select_)) {
  2154. // Delete all previous arguments
  2155. ctx.callout_handle_->deleteAllArguments();
  2156. // Pass necessary arguments
  2157. // Subnet from which we do the allocation. Convert the general subnet
  2158. // pointer to a pointer to a Subnet4. Note that because we are using
  2159. // boost smart pointers here, we need to do the cast using the boost
  2160. // version of dynamic_pointer_cast.
  2161. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  2162. ctx.callout_handle_->setArgument("subnet4", subnet4);
  2163. // Is this solicit (fake = true) or request (fake = false)
  2164. ctx.callout_handle_->setArgument("fake_allocation",
  2165. ctx.fake_allocation_);
  2166. // The lease that will be assigned to a client
  2167. ctx.callout_handle_->setArgument("lease4", expired);
  2168. // Call the callouts
  2169. HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
  2170. // Callouts decided to skip the action. This means that the lease is not
  2171. // assigned, so the client will get NoAddrAvail as a result. The lease
  2172. // won't be inserted into the database.
  2173. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  2174. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  2175. DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  2176. return (Lease4Ptr());
  2177. }
  2178. /// @todo: add support for DROP
  2179. // Let's use whatever callout returned. Hopefully it is the same lease
  2180. // we handed to it.
  2181. ctx.callout_handle_->getArgument("lease4", expired);
  2182. }
  2183. if (!ctx.fake_allocation_) {
  2184. // for REQUEST we do update the lease
  2185. LeaseMgrFactory::instance().updateLease4(expired);
  2186. }
  2187. // We do nothing for SOLICIT. We'll just update database when
  2188. // the client gets back to us with REQUEST message.
  2189. // it's not really expired at this stage anymore - let's return it as
  2190. // an updated lease
  2191. return (expired);
  2192. }
  2193. Lease4Ptr
  2194. AllocEngine::allocateOrReuseLease4(const IOAddress& candidate, ClientContext4& ctx) {
  2195. ctx.conflicting_lease_.reset();
  2196. Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
  2197. if (exist_lease) {
  2198. if (exist_lease->expired()) {
  2199. ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
  2200. return (reuseExpiredLease4(exist_lease, ctx));
  2201. } else {
  2202. // If there is a lease and it is not expired, pass this lease back
  2203. // to the caller in the context. The caller may need to know
  2204. // which lease we're conflicting with.
  2205. ctx.conflicting_lease_ = exist_lease;
  2206. }
  2207. } else {
  2208. return (createLease4(ctx, candidate));
  2209. }
  2210. return (Lease4Ptr());
  2211. }
  2212. Lease4Ptr
  2213. AllocEngine::allocateUnreservedLease4(ClientContext4& ctx) {
  2214. Lease4Ptr new_lease;
  2215. AllocatorPtr allocator = getAllocator(Lease::TYPE_V4);
  2216. const uint64_t max_attempts = (attempts_ > 0 ? attempts_ :
  2217. ctx.subnet_->getPoolCapacity(Lease::TYPE_V4));
  2218. for (uint64_t i = 0; i < max_attempts; ++i) {
  2219. IOAddress candidate = allocator->pickAddress(ctx.subnet_, ctx.clientid_,
  2220. ctx.requested_address_);
  2221. // If address is not reserved for another client, try to allocate it.
  2222. if (!addressReserved(candidate, ctx)) {
  2223. // The call below will return the non-NULL pointer if we
  2224. // successfully allocate this lease. This means that the
  2225. // address is not in use by another client.
  2226. new_lease = allocateOrReuseLease4(candidate, ctx);
  2227. if (new_lease) {
  2228. return (new_lease);
  2229. }
  2230. }
  2231. }
  2232. // Unable to allocate an address, return an empty lease.
  2233. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V4_ALLOC_FAIL)
  2234. .arg(ctx.query_->getLabel())
  2235. .arg(max_attempts);
  2236. return (new_lease);
  2237. }
  2238. void
  2239. AllocEngine::updateLease4Information(const Lease4Ptr& lease,
  2240. AllocEngine::ClientContext4& ctx) const {
  2241. lease->subnet_id_ = ctx.subnet_->getID();
  2242. lease->hwaddr_ = ctx.hwaddr_;
  2243. lease->client_id_ = ctx.clientid_;
  2244. lease->cltt_ = time(NULL);
  2245. lease->t1_ = ctx.subnet_->getT1();
  2246. lease->t2_ = ctx.subnet_->getT2();
  2247. lease->valid_lft_ = ctx.subnet_->getValid();
  2248. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  2249. lease->fqdn_rev_ = ctx.rev_dns_update_;
  2250. lease->hostname_ = ctx.hostname_;
  2251. }
  2252. bool
  2253. AllocEngine::conditionalExtendLifetime(Lease& lease) const {
  2254. lease.cltt_ = time(NULL);
  2255. return (true);
  2256. }
  2257. }; // end of isc::dhcp namespace
  2258. }; // end of isc namespace