alloc_engine.cc 112 KB

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