alloc_engine.cc 105 KB

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