alloc_engine.cc 120 KB

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