alloc_engine.cc 131 KB

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