alloc_engine.cc 115 KB

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