alloc_engine.cc 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869
  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. // Enable copying options from the packet within hook library.
  875. ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
  876. // Pass necessary arguments
  877. // Pass the original packet
  878. ctx.callout_handle_->setArgument("query6", ctx.query_);
  879. // Subnet from which we do the allocation
  880. ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
  881. // Is this solicit (fake = true) or request (fake = false)
  882. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  883. // The lease that will be assigned to a client
  884. ctx.callout_handle_->setArgument("lease6", expired);
  885. // Call the callouts
  886. HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
  887. // Callouts decided to skip the action. This means that the lease is not
  888. // assigned, so the client will get NoAddrAvail as a result. The lease
  889. // won't be inserted into the database.
  890. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  891. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  892. return (Lease6Ptr());
  893. }
  894. /// @todo: Add support for DROP status
  895. // Let's use whatever callout returned. Hopefully it is the same lease
  896. // we handed to it.
  897. ctx.callout_handle_->getArgument("lease6", expired);
  898. }
  899. if (!ctx.fake_allocation_) {
  900. // for REQUEST we do update the lease
  901. LeaseMgrFactory::instance().updateLease6(expired);
  902. }
  903. // We do nothing for SOLICIT. We'll just update database when
  904. // the client gets back to us with REQUEST message.
  905. // it's not really expired at this stage anymore - let's return it as
  906. // an updated lease
  907. return (expired);
  908. }
  909. Lease6Ptr AllocEngine::createLease6(ClientContext6& ctx,
  910. const IOAddress& addr,
  911. uint8_t prefix_len) {
  912. if (ctx.currentIA().type_ != Lease::TYPE_PD) {
  913. prefix_len = 128; // non-PD lease types must be always /128
  914. }
  915. Lease6Ptr lease(new Lease6(ctx.currentIA().type_, addr, ctx.duid_,
  916. ctx.currentIA().iaid_, ctx.subnet_->getPreferred(),
  917. ctx.subnet_->getValid(), ctx.subnet_->getT1(),
  918. ctx.subnet_->getT2(), ctx.subnet_->getID(),
  919. ctx.hwaddr_, prefix_len));
  920. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  921. lease->fqdn_rev_ = ctx.rev_dns_update_;
  922. lease->hostname_ = ctx.hostname_;
  923. // Let's execute all callouts registered for lease6_select
  924. if (ctx.callout_handle_ &&
  925. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  926. // Delete all previous arguments
  927. ctx.callout_handle_->deleteAllArguments();
  928. // Enable copying options from the packet within hook library.
  929. ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
  930. // Pass necessary arguments
  931. // Pass the original packet
  932. ctx.callout_handle_->setArgument("query6", ctx.query_);
  933. // Subnet from which we do the allocation
  934. ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
  935. // Is this solicit (fake = true) or request (fake = false)
  936. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  937. ctx.callout_handle_->setArgument("lease6", lease);
  938. // This is the first callout, so no need to clear any arguments
  939. HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
  940. // Callouts decided to skip the action. This means that the lease is not
  941. // assigned, so the client will get NoAddrAvail as a result. The lease
  942. // won't be inserted into the database.
  943. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  944. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  945. return (Lease6Ptr());
  946. }
  947. // Let's use whatever callout returned. Hopefully it is the same lease
  948. // we handed to it.
  949. ctx.callout_handle_->getArgument("lease6", lease);
  950. }
  951. if (!ctx.fake_allocation_) {
  952. // That is a real (REQUEST) allocation
  953. bool status = LeaseMgrFactory::instance().addLease(lease);
  954. if (status) {
  955. // The lease insertion succeeded - if the lease is in the
  956. // current subnet lets bump up the statistic.
  957. if (ctx.subnet_->inPool(ctx.currentIA().type_, addr)) {
  958. StatsMgr::instance().addValue(
  959. StatsMgr::generateName("subnet", ctx.subnet_->getID(),
  960. ctx.currentIA().type_ == Lease::TYPE_NA ?
  961. "assigned-nas" : "assigned-pds"),
  962. static_cast<int64_t>(1));
  963. }
  964. return (lease);
  965. } else {
  966. // One of many failures with LeaseMgr (e.g. lost connection to the
  967. // database, database failed etc.). One notable case for that
  968. // is that we are working in multi-process mode and we lost a race
  969. // (some other process got that address first)
  970. return (Lease6Ptr());
  971. }
  972. } else {
  973. // That is only fake (SOLICIT without rapid-commit) allocation
  974. // It is for advertise only. We should not insert the lease into LeaseMgr,
  975. // but rather check that we could have inserted it.
  976. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(
  977. Lease::TYPE_NA, addr);
  978. if (!existing) {
  979. return (lease);
  980. } else {
  981. return (Lease6Ptr());
  982. }
  983. }
  984. }
  985. Lease6Collection
  986. AllocEngine::renewLeases6(ClientContext6& ctx) {
  987. try {
  988. if (!ctx.subnet_) {
  989. isc_throw(InvalidOperation, "Subnet is required for allocation");
  990. }
  991. if (!ctx.duid_) {
  992. isc_throw(InvalidOperation, "DUID is mandatory for allocation");
  993. }
  994. // Check if there are any leases for this client.
  995. Lease6Collection leases = LeaseMgrFactory::instance()
  996. .getLeases6(ctx.currentIA().type_, *ctx.duid_,
  997. ctx.currentIA().iaid_, ctx.subnet_->getID());
  998. if (!leases.empty()) {
  999. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1000. ALLOC_ENGINE_V6_RENEW_REMOVE_RESERVED)
  1001. .arg(ctx.query_->getLabel());
  1002. // Check if the existing leases are reserved for someone else.
  1003. // If they're not, we're ok to keep using them.
  1004. removeNonmatchingReservedLeases6(ctx, leases);
  1005. }
  1006. if (ctx.host_) {
  1007. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1008. ALLOC_ENGINE_V6_RENEW_HR)
  1009. .arg(ctx.query_->getLabel());
  1010. // If we have host reservation, allocate those leases.
  1011. allocateReservedLeases6(ctx, leases);
  1012. // There's one more check to do. Let's remove leases that are not
  1013. // matching reservations, i.e. if client X has address A, but there's
  1014. // a reservation for address B, we should release A and reassign B.
  1015. // Caveat: do this only if we have at least one reserved address.
  1016. removeNonreservedLeases6(ctx, leases);
  1017. }
  1018. // If we happen to removed all leases, get something new for this guy.
  1019. // Depending on the configuration, we may enable or disable granting
  1020. // new leases during renewals. This is controlled with the
  1021. // allow_new_leases_in_renewals_ field.
  1022. if (leases.empty()) {
  1023. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1024. ALLOC_ENGINE_V6_EXTEND_ALLOC_UNRESERVED)
  1025. .arg(ctx.query_->getLabel());
  1026. leases = allocateUnreservedLeases6(ctx);
  1027. }
  1028. // Extend all existing leases that passed all checks.
  1029. for (Lease6Collection::iterator l = leases.begin(); l != leases.end(); ++l) {
  1030. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL,
  1031. ALLOC_ENGINE_V6_EXTEND_LEASE)
  1032. .arg(ctx.query_->getLabel())
  1033. .arg((*l)->typeToText((*l)->type_))
  1034. .arg((*l)->addr_);
  1035. extendLease6(ctx, *l);
  1036. }
  1037. if (!leases.empty()) {
  1038. // If there are any leases allocated, let's store in them in the
  1039. // IA context so as they are available when we process subsequent
  1040. // IAs.
  1041. BOOST_FOREACH(Lease6Ptr lease, leases) {
  1042. ctx.addAllocatedResource(lease->addr_, lease->prefixlen_);
  1043. }
  1044. }
  1045. return (leases);
  1046. } catch (const isc::Exception& e) {
  1047. // Some other error, return an empty lease.
  1048. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_EXTEND_ERROR)
  1049. .arg(ctx.query_->getLabel())
  1050. .arg(e.what());
  1051. }
  1052. return (Lease6Collection());
  1053. }
  1054. void
  1055. AllocEngine::extendLease6(ClientContext6& ctx, Lease6Ptr lease) {
  1056. if (!lease || !ctx.subnet_) {
  1057. return;
  1058. }
  1059. // Check if the lease still belongs to the subnet. If it doesn't,
  1060. // we'll need to remove it.
  1061. if ((lease->type_ != Lease::TYPE_PD) && !ctx.subnet_->inRange(lease->addr_)) {
  1062. // Oh dear, the lease is no longer valid. We need to get rid of it.
  1063. // Remove this lease from LeaseMgr
  1064. LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1065. // Updated DNS if required.
  1066. queueNCR(CHG_REMOVE, lease);
  1067. // Need to decrease statistic for assigned addresses.
  1068. StatsMgr::instance().addValue(
  1069. StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-nas"),
  1070. static_cast<int64_t>(-1));
  1071. // Add it to the removed leases list.
  1072. ctx.currentIA().old_leases_.push_back(lease);
  1073. return;
  1074. }
  1075. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA,
  1076. ALLOC_ENGINE_V6_EXTEND_LEASE_DATA)
  1077. .arg(ctx.query_->getLabel())
  1078. .arg(lease->toText());
  1079. // Keep the old data in case the callout tells us to skip update.
  1080. Lease6Ptr old_data(new Lease6(*lease));
  1081. lease->preferred_lft_ = ctx.subnet_->getPreferred();
  1082. lease->valid_lft_ = ctx.subnet_->getValid();
  1083. lease->t1_ = ctx.subnet_->getT1();
  1084. lease->t2_ = ctx.subnet_->getT2();
  1085. lease->hostname_ = ctx.hostname_;
  1086. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  1087. lease->fqdn_rev_ = ctx.rev_dns_update_;
  1088. lease->hwaddr_ = ctx.hwaddr_;
  1089. lease->state_ = Lease::STATE_DEFAULT;
  1090. // Extend lease lifetime if it is time to extend it.
  1091. conditionalExtendLifetime(*lease);
  1092. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA,
  1093. ALLOC_ENGINE_V6_EXTEND_NEW_LEASE_DATA)
  1094. .arg(ctx.query_->getLabel())
  1095. .arg(lease->toText());
  1096. bool skip = false;
  1097. // Get the callouts specific for the processed message and execute them.
  1098. int hook_point = ctx.query_->getType() == DHCPV6_RENEW ?
  1099. Hooks.hook_index_lease6_renew_ : Hooks.hook_index_lease6_rebind_;
  1100. if (HooksManager::calloutsPresent(hook_point)) {
  1101. CalloutHandlePtr callout_handle = ctx.callout_handle_;
  1102. // Delete all previous arguments
  1103. callout_handle->deleteAllArguments();
  1104. // Enable copying options from the packet within hook library.
  1105. ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
  1106. // Pass the original packet
  1107. callout_handle->setArgument("query6", ctx.query_);
  1108. // Pass the lease to be updated
  1109. callout_handle->setArgument("lease6", lease);
  1110. // Pass the IA option to be sent in response
  1111. if (lease->type_ == Lease::TYPE_NA) {
  1112. callout_handle->setArgument("ia_na", ctx.currentIA().ia_rsp_);
  1113. } else {
  1114. callout_handle->setArgument("ia_pd", ctx.currentIA().ia_rsp_);
  1115. }
  1116. // Call all installed callouts
  1117. HooksManager::callCallouts(hook_point, *callout_handle);
  1118. // Callouts decided to skip the next processing step. The next
  1119. // processing step would actually renew the lease, so skip at this
  1120. // stage means "keep the old lease as it is".
  1121. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  1122. skip = true;
  1123. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  1124. DHCPSRV_HOOK_LEASE6_EXTEND_SKIP)
  1125. .arg(ctx.query_->getName());
  1126. }
  1127. /// @todo: Add support for DROP status
  1128. }
  1129. if (!skip) {
  1130. // If the lease we're renewing has expired, we need to reclaim this
  1131. // lease before we can renew it.
  1132. if (old_data->expired()) {
  1133. reclaimExpiredLease(old_data, ctx.callout_handle_);
  1134. } else {
  1135. if (!lease->hasIdenticalFqdn(*old_data)) {
  1136. // We're not reclaiming the lease but since the FQDN has changed
  1137. // we have to at least send NCR.
  1138. queueNCR(CHG_REMOVE, old_data);
  1139. }
  1140. }
  1141. // Now that the lease has been reclaimed, we can go ahead and update it
  1142. // in the lease database.
  1143. LeaseMgrFactory::instance().updateLease6(lease);
  1144. } else {
  1145. // Copy back the original date to the lease. For MySQL it doesn't make
  1146. // much sense, but for memfile, the Lease6Ptr points to the actual lease
  1147. // in memfile, so the actual update is performed when we manipulate
  1148. // fields of returned Lease6Ptr, the actual updateLease6() is no-op.
  1149. *lease = *old_data;
  1150. }
  1151. // Add the old lease to the changed lease list. This allows the server
  1152. // to make decisions regarding DNS updates.
  1153. ctx.currentIA().changed_leases_.push_back(old_data);
  1154. }
  1155. Lease6Collection
  1156. AllocEngine::updateLeaseData(ClientContext6& ctx, const Lease6Collection& leases) {
  1157. Lease6Collection updated_leases;
  1158. bool remove_queued = false;
  1159. for (Lease6Collection::const_iterator lease_it = leases.begin();
  1160. lease_it != leases.end(); ++lease_it) {
  1161. Lease6Ptr lease(new Lease6(**lease_it));
  1162. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  1163. lease->fqdn_rev_ = ctx.rev_dns_update_;
  1164. lease->hostname_ = ctx.hostname_;
  1165. if (!ctx.fake_allocation_) {
  1166. bool fqdn_changed = ((lease->type_ != Lease::TYPE_PD) &&
  1167. !(lease->hasIdenticalFqdn(**lease_it)));
  1168. if (conditionalExtendLifetime(*lease) || fqdn_changed) {
  1169. ctx.currentIA().changed_leases_.push_back(*lease_it);
  1170. LeaseMgrFactory::instance().updateLease6(lease);
  1171. // If the FQDN differs, remove existing DNS entries.
  1172. // We only need one remove.
  1173. if (fqdn_changed && !remove_queued) {
  1174. queueNCR(CHG_REMOVE, *lease_it);
  1175. remove_queued = true;
  1176. }
  1177. }
  1178. }
  1179. updated_leases.push_back(lease);
  1180. }
  1181. return (updated_leases);
  1182. }
  1183. void
  1184. AllocEngine::reclaimExpiredLeases6(const size_t max_leases, const uint16_t timeout,
  1185. const bool remove_lease,
  1186. const uint16_t max_unwarned_cycles) {
  1187. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1188. ALLOC_ENGINE_V6_LEASES_RECLAMATION_START)
  1189. .arg(max_leases)
  1190. .arg(timeout);
  1191. // Create stopwatch and automatically start it to measure the time
  1192. // taken by the routine.
  1193. util::Stopwatch stopwatch;
  1194. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1195. // This value indicates if we have been able to deal with all expired
  1196. // leases in this pass.
  1197. bool incomplete_reclamation = false;
  1198. Lease6Collection leases;
  1199. // The value of 0 has a special meaning - reclaim all.
  1200. if (max_leases > 0) {
  1201. // If the value is non-zero, the caller has limited the number of
  1202. // leases to reclaim. We obtain one lease more to see if there will
  1203. // be still leases left after this pass.
  1204. lease_mgr.getExpiredLeases6(leases, max_leases + 1);
  1205. // There are more leases expired leases than we will process in this
  1206. // pass, so we should mark it as an incomplete reclamation. We also
  1207. // remove this extra lease (which we don't want to process anyway)
  1208. // from the collection.
  1209. if (leases.size() > max_leases) {
  1210. leases.pop_back();
  1211. incomplete_reclamation = true;
  1212. }
  1213. } else {
  1214. // If there is no limitation on the number of leases to reclaim,
  1215. // we will try to process all. Hence, we don't mark it as incomplete
  1216. // reclamation just yet.
  1217. lease_mgr.getExpiredLeases6(leases, max_leases);
  1218. }
  1219. // Do not initialize the callout handle until we know if there are any
  1220. // lease6_expire callouts installed.
  1221. CalloutHandlePtr callout_handle;
  1222. if (!leases.empty() &&
  1223. HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease6_expire_)) {
  1224. callout_handle = HooksManager::createCalloutHandle();
  1225. }
  1226. size_t leases_processed = 0;
  1227. BOOST_FOREACH(Lease6Ptr lease, leases) {
  1228. try {
  1229. // Reclaim the lease.
  1230. reclaimExpiredLease(lease, remove_lease, callout_handle);
  1231. ++leases_processed;
  1232. } catch (const std::exception& ex) {
  1233. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_LEASE_RECLAMATION_FAILED)
  1234. .arg(lease->addr_.toText())
  1235. .arg(ex.what());
  1236. }
  1237. // Check if we have hit the timeout for running reclamation routine and
  1238. // return if we have. We're checking it here, because we always want to
  1239. // allow reclaiming at least one lease.
  1240. if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
  1241. // Timeout. This will likely mean that we haven't been able to process
  1242. // all leases we wanted to process. The reclamation pass will be
  1243. // probably marked as incomplete.
  1244. if (!incomplete_reclamation) {
  1245. if (leases_processed < leases.size()) {
  1246. incomplete_reclamation = true;
  1247. }
  1248. }
  1249. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1250. ALLOC_ENGINE_V6_LEASES_RECLAMATION_TIMEOUT)
  1251. .arg(timeout);
  1252. break;
  1253. }
  1254. }
  1255. // Stop measuring the time.
  1256. stopwatch.stop();
  1257. // Mark completion of the lease reclamation routine and present some stats.
  1258. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1259. ALLOC_ENGINE_V6_LEASES_RECLAMATION_COMPLETE)
  1260. .arg(leases_processed)
  1261. .arg(stopwatch.logFormatTotalDuration());
  1262. // Check if this was an incomplete reclamation and increase the number of
  1263. // consecutive incomplete reclamations.
  1264. if (incomplete_reclamation) {
  1265. ++incomplete_v6_reclamations_;
  1266. // If the number of incomplete reclamations is beyond the threshold, we
  1267. // need to issue a warning.
  1268. if ((max_unwarned_cycles > 0) &&
  1269. (incomplete_v6_reclamations_ > max_unwarned_cycles)) {
  1270. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V6_LEASES_RECLAMATION_SLOW)
  1271. .arg(max_unwarned_cycles);
  1272. // We issued a warning, so let's now reset the counter.
  1273. incomplete_v6_reclamations_ = 0;
  1274. }
  1275. } else {
  1276. // This was a complete reclamation, so let's reset the counter.
  1277. incomplete_v6_reclamations_ = 0;
  1278. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1279. ALLOC_ENGINE_V6_NO_MORE_EXPIRED_LEASES);
  1280. }
  1281. }
  1282. void
  1283. AllocEngine::deleteExpiredReclaimedLeases6(const uint32_t secs) {
  1284. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1285. ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE)
  1286. .arg(secs);
  1287. uint64_t deleted_leases = 0;
  1288. try {
  1289. // Try to delete leases from the lease database.
  1290. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1291. deleted_leases = lease_mgr.deleteExpiredReclaimedLeases6(secs);
  1292. } catch (const std::exception& ex) {
  1293. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE_FAILED)
  1294. .arg(ex.what());
  1295. }
  1296. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1297. ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE_COMPLETE)
  1298. .arg(deleted_leases);
  1299. }
  1300. void
  1301. AllocEngine::reclaimExpiredLeases4(const size_t max_leases, const uint16_t timeout,
  1302. const bool remove_lease,
  1303. const uint16_t max_unwarned_cycles) {
  1304. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1305. ALLOC_ENGINE_V4_LEASES_RECLAMATION_START)
  1306. .arg(max_leases)
  1307. .arg(timeout);
  1308. // Create stopwatch and automatically start it to measure the time
  1309. // taken by the routine.
  1310. util::Stopwatch stopwatch;
  1311. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1312. // This value indicates if we have been able to deal with all expired
  1313. // leases in this pass.
  1314. bool incomplete_reclamation = false;
  1315. Lease4Collection leases;
  1316. // The value of 0 has a special meaning - reclaim all.
  1317. if (max_leases > 0) {
  1318. // If the value is non-zero, the caller has limited the number of
  1319. // leases to reclaim. We obtain one lease more to see if there will
  1320. // be still leases left after this pass.
  1321. lease_mgr.getExpiredLeases4(leases, max_leases + 1);
  1322. // There are more leases expired leases than we will process in this
  1323. // pass, so we should mark it as an incomplete reclamation. We also
  1324. // remove this extra lease (which we don't want to process anyway)
  1325. // from the collection.
  1326. if (leases.size() > max_leases) {
  1327. leases.pop_back();
  1328. incomplete_reclamation = true;
  1329. }
  1330. } else {
  1331. // If there is no limitation on the number of leases to reclaim,
  1332. // we will try to process all. Hence, we don't mark it as incomplete
  1333. // reclamation just yet.
  1334. lease_mgr.getExpiredLeases4(leases, max_leases);
  1335. }
  1336. // Do not initialize the callout handle until we know if there are any
  1337. // lease4_expire callouts installed.
  1338. CalloutHandlePtr callout_handle;
  1339. if (!leases.empty() &&
  1340. HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease4_expire_)) {
  1341. callout_handle = HooksManager::createCalloutHandle();
  1342. }
  1343. size_t leases_processed = 0;
  1344. BOOST_FOREACH(Lease4Ptr lease, leases) {
  1345. try {
  1346. // Reclaim the lease.
  1347. reclaimExpiredLease(lease, remove_lease, callout_handle);
  1348. ++leases_processed;
  1349. } catch (const std::exception& ex) {
  1350. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V4_LEASE_RECLAMATION_FAILED)
  1351. .arg(lease->addr_.toText())
  1352. .arg(ex.what());
  1353. }
  1354. // Check if we have hit the timeout for running reclamation routine and
  1355. // return if we have. We're checking it here, because we always want to
  1356. // allow reclaiming at least one lease.
  1357. if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
  1358. // Timeout. This will likely mean that we haven't been able to process
  1359. // all leases we wanted to process. The reclamation pass will be
  1360. // probably marked as incomplete.
  1361. if (!incomplete_reclamation) {
  1362. if (leases_processed < leases.size()) {
  1363. incomplete_reclamation = true;
  1364. }
  1365. }
  1366. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1367. ALLOC_ENGINE_V4_LEASES_RECLAMATION_TIMEOUT)
  1368. .arg(timeout);
  1369. break;
  1370. }
  1371. }
  1372. // Stop measuring the time.
  1373. stopwatch.stop();
  1374. // Mark completion of the lease reclamation routine and present some stats.
  1375. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1376. ALLOC_ENGINE_V4_LEASES_RECLAMATION_COMPLETE)
  1377. .arg(leases_processed)
  1378. .arg(stopwatch.logFormatTotalDuration());
  1379. // Check if this was an incomplete reclamation and increase the number of
  1380. // consecutive incomplete reclamations.
  1381. if (incomplete_reclamation) {
  1382. ++incomplete_v4_reclamations_;
  1383. // If the number of incomplete reclamations is beyond the threshold, we
  1384. // need to issue a warning.
  1385. if ((max_unwarned_cycles > 0) &&
  1386. (incomplete_v4_reclamations_ > max_unwarned_cycles)) {
  1387. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V4_LEASES_RECLAMATION_SLOW)
  1388. .arg(max_unwarned_cycles);
  1389. // We issued a warning, so let's now reset the counter.
  1390. incomplete_v4_reclamations_ = 0;
  1391. }
  1392. } else {
  1393. // This was a complete reclamation, so let's reset the counter.
  1394. incomplete_v4_reclamations_ = 0;
  1395. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1396. ALLOC_ENGINE_V4_NO_MORE_EXPIRED_LEASES);
  1397. }
  1398. }
  1399. template<typename LeasePtrType>
  1400. void
  1401. AllocEngine::reclaimExpiredLease(const LeasePtrType& lease, const bool remove_lease,
  1402. const CalloutHandlePtr& callout_handle) {
  1403. reclaimExpiredLease(lease, remove_lease ? DB_RECLAIM_REMOVE : DB_RECLAIM_UPDATE,
  1404. callout_handle);
  1405. }
  1406. template<typename LeasePtrType>
  1407. void
  1408. AllocEngine::reclaimExpiredLease(const LeasePtrType& lease,
  1409. const CalloutHandlePtr& callout_handle) {
  1410. // This variant of the method is used by the code which allocates or
  1411. // renews leases. It may be the case that the lease has already been
  1412. // reclaimed, so there is nothing to do.
  1413. if (!lease->stateExpiredReclaimed()) {
  1414. reclaimExpiredLease(lease, DB_RECLAIM_LEAVE_UNCHANGED, callout_handle);
  1415. }
  1416. }
  1417. void
  1418. AllocEngine::reclaimExpiredLease(const Lease6Ptr& lease,
  1419. const DbReclaimMode& reclaim_mode,
  1420. const CalloutHandlePtr& callout_handle) {
  1421. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1422. ALLOC_ENGINE_V6_LEASE_RECLAIM)
  1423. .arg(Pkt6::makeLabel(lease->duid_, lease->hwaddr_))
  1424. .arg(lease->addr_.toText())
  1425. .arg(static_cast<int>(lease->prefixlen_));
  1426. // The skip flag indicates if the callouts have taken responsibility
  1427. // for reclaiming the lease. The callout will set this to true if
  1428. // it reclaims the lease itself. In this case the reclamation routine
  1429. // will not update DNS nor update the database.
  1430. bool skipped = false;
  1431. if (callout_handle) {
  1432. callout_handle->deleteAllArguments();
  1433. callout_handle->setArgument("lease6", lease);
  1434. callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
  1435. HooksManager::callCallouts(Hooks.hook_index_lease6_expire_,
  1436. *callout_handle);
  1437. skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
  1438. }
  1439. /// @todo: Maybe add support for DROP status?
  1440. /// Not sure if we need to support every possible status everywhere.
  1441. if (!skipped) {
  1442. // Generate removal name change request for D2, if required.
  1443. // This will return immediately if the DNS wasn't updated
  1444. // when the lease was created.
  1445. queueNCR(CHG_REMOVE, lease);
  1446. // Let's check if the lease that just expired is in DECLINED state.
  1447. // If it is, we need to perform a couple extra steps.
  1448. bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
  1449. if (lease->state_ == Lease::STATE_DECLINED) {
  1450. // Do extra steps required for declined lease reclamation:
  1451. // - call the recover hook
  1452. // - bump decline-related stats
  1453. // - log separate message
  1454. // There's no point in keeping a declined lease after its
  1455. // reclamation. A declined lease doesn't have any client
  1456. // identifying information anymore. So we'll flag it for
  1457. // removal unless the hook has set the skip flag.
  1458. remove_lease = reclaimDeclined(lease);
  1459. }
  1460. if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
  1461. // Reclaim the lease - depending on the configuration, set the
  1462. // expired-reclaimed state or simply remove it.
  1463. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1464. reclaimLeaseInDatabase<Lease6Ptr>(lease, remove_lease,
  1465. boost::bind(&LeaseMgr::updateLease6,
  1466. &lease_mgr, _1));
  1467. }
  1468. }
  1469. // Update statistics.
  1470. // Decrease number of assigned leases.
  1471. if (lease->type_ == Lease::TYPE_NA) {
  1472. // IA_NA
  1473. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1474. lease->subnet_id_,
  1475. "assigned-nas"),
  1476. int64_t(-1));
  1477. } else if (lease->type_ == Lease::TYPE_PD) {
  1478. // IA_PD
  1479. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1480. lease->subnet_id_,
  1481. "assigned-pds"),
  1482. int64_t(-1));
  1483. }
  1484. // Increase total number of reclaimed leases.
  1485. StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
  1486. // Increase number of reclaimed leases for a subnet.
  1487. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1488. lease->subnet_id_,
  1489. "reclaimed-leases"),
  1490. int64_t(1));
  1491. }
  1492. void
  1493. AllocEngine::reclaimExpiredLease(const Lease4Ptr& lease,
  1494. const DbReclaimMode& reclaim_mode,
  1495. const CalloutHandlePtr& callout_handle) {
  1496. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1497. ALLOC_ENGINE_V4_LEASE_RECLAIM)
  1498. .arg(Pkt4::makeLabel(lease->hwaddr_, lease->client_id_))
  1499. .arg(lease->addr_.toText());
  1500. // The skip flag indicates if the callouts have taken responsibility
  1501. // for reclaiming the lease. The callout will set this to true if
  1502. // it reclaims the lease itself. In this case the reclamation routine
  1503. // will not update DNS nor update the database.
  1504. bool skipped = false;
  1505. if (callout_handle) {
  1506. callout_handle->deleteAllArguments();
  1507. callout_handle->setArgument("lease4", lease);
  1508. callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
  1509. HooksManager::callCallouts(Hooks.hook_index_lease4_expire_,
  1510. *callout_handle);
  1511. skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
  1512. }
  1513. /// @todo: Maybe add support for DROP status?
  1514. /// Not sure if we need to support every possible status everywhere.
  1515. if (!skipped) {
  1516. // Generate removal name change request for D2, if required.
  1517. // This will return immediatelly if the DNS wasn't updated
  1518. // when the lease was created.
  1519. queueNCR(CHG_REMOVE, lease);
  1520. // Let's check if the lease that just expired is in DECLINED state.
  1521. // If it is, we need to perform a couple extra steps.
  1522. bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
  1523. if (lease->state_ == Lease::STATE_DECLINED) {
  1524. // Do extra steps required for declined lease reclamation:
  1525. // - call the recover hook
  1526. // - bump decline-related stats
  1527. // - log separate message
  1528. // There's no point in keeping a declined lease after its
  1529. // reclamation. A declined lease doesn't have any client
  1530. // identifying information anymore. So we'll flag it for
  1531. // removal unless the hook has set the skip flag.
  1532. remove_lease = reclaimDeclined(lease);
  1533. }
  1534. if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
  1535. // Reclaim the lease - depending on the configuration, set the
  1536. // expired-reclaimed state or simply remove it.
  1537. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1538. reclaimLeaseInDatabase<Lease4Ptr>(lease, remove_lease,
  1539. boost::bind(&LeaseMgr::updateLease4,
  1540. &lease_mgr, _1));
  1541. }
  1542. }
  1543. // Update statistics.
  1544. // Decrease number of assigned addresses.
  1545. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1546. lease->subnet_id_,
  1547. "assigned-addresses"),
  1548. int64_t(-1));
  1549. // Increase total number of reclaimed leases.
  1550. StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
  1551. // Increase number of reclaimed leases for a subnet.
  1552. StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
  1553. lease->subnet_id_,
  1554. "reclaimed-leases"),
  1555. int64_t(1));
  1556. }
  1557. void
  1558. AllocEngine::deleteExpiredReclaimedLeases4(const uint32_t secs) {
  1559. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1560. ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE)
  1561. .arg(secs);
  1562. uint64_t deleted_leases = 0;
  1563. try {
  1564. // Try to delete leases from the lease database.
  1565. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1566. deleted_leases = lease_mgr.deleteExpiredReclaimedLeases4(secs);
  1567. } catch (const std::exception& ex) {
  1568. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE_FAILED)
  1569. .arg(ex.what());
  1570. }
  1571. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1572. ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE_COMPLETE)
  1573. .arg(deleted_leases);
  1574. }
  1575. bool
  1576. AllocEngine::reclaimDeclined(const Lease4Ptr& lease) {
  1577. if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
  1578. return (true);
  1579. }
  1580. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease4_recover_)) {
  1581. // Let's use a static callout handle. It will be initialized the first
  1582. // time lease4_recover is called and will keep to that value.
  1583. static CalloutHandlePtr callout_handle;
  1584. if (!callout_handle) {
  1585. callout_handle = HooksManager::createCalloutHandle();
  1586. }
  1587. // Delete all previous arguments
  1588. callout_handle->deleteAllArguments();
  1589. // Pass necessary arguments
  1590. callout_handle->setArgument("lease4", lease);
  1591. // Call the callouts
  1592. HooksManager::callCallouts(Hooks.hook_index_lease4_recover_, *callout_handle);
  1593. // Callouts decided to skip the action. This means that the lease is not
  1594. // assigned, so the client will get NoAddrAvail as a result. The lease
  1595. // won't be inserted into the database.
  1596. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  1597. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_RECOVER_SKIP)
  1598. .arg(lease->addr_.toText());
  1599. return (false);
  1600. }
  1601. }
  1602. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V4_DECLINED_RECOVERED)
  1603. .arg(lease->addr_.toText())
  1604. .arg(lease->valid_lft_);
  1605. StatsMgr& stats_mgr = StatsMgr::instance();
  1606. // Decrease subnet specific counter for currently declined addresses
  1607. stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
  1608. "declined-addresses"), static_cast<int64_t>(-1));
  1609. // Decrease global counter for declined addresses
  1610. stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
  1611. stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
  1612. stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
  1613. "reclaimed-declined-addresses"), static_cast<int64_t>(1));
  1614. // Note that we do not touch assigned-addresses counters. Those are
  1615. // modified in whatever code calls this method.
  1616. return (true);
  1617. }
  1618. bool
  1619. AllocEngine::reclaimDeclined(const Lease6Ptr& lease) {
  1620. if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
  1621. return (true);
  1622. }
  1623. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease6_recover_)) {
  1624. // Let's use a static callout handle. It will be initialized the first
  1625. // time lease6_recover is called and will keep to that value.
  1626. static CalloutHandlePtr callout_handle;
  1627. if (!callout_handle) {
  1628. callout_handle = HooksManager::createCalloutHandle();
  1629. }
  1630. // Delete all previous arguments
  1631. callout_handle->deleteAllArguments();
  1632. // Pass necessary arguments
  1633. callout_handle->setArgument("lease6", lease);
  1634. // Call the callouts
  1635. HooksManager::callCallouts(Hooks.hook_index_lease6_recover_, *callout_handle);
  1636. // Callouts decided to skip the action. This means that the lease is not
  1637. // assigned, so the client will get NoAddrAvail as a result. The lease
  1638. // won't be inserted into the database.
  1639. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  1640. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_RECOVER_SKIP)
  1641. .arg(lease->addr_.toText());
  1642. return (false);
  1643. }
  1644. }
  1645. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_DECLINED_RECOVERED)
  1646. .arg(lease->addr_.toText())
  1647. .arg(lease->valid_lft_);
  1648. StatsMgr& stats_mgr = StatsMgr::instance();
  1649. // Decrease subnet specific counter for currently declined addresses
  1650. stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
  1651. "declined-addresses"), static_cast<int64_t>(-1));
  1652. // Decrease global counter for declined addresses
  1653. stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
  1654. stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
  1655. stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
  1656. "reclaimed-declined-addresses"), static_cast<int64_t>(1));
  1657. // Note that we do not touch assigned-addresses counters. Those are
  1658. // modified in whatever code calls this method.
  1659. return (true);
  1660. }
  1661. template<typename LeasePtrType>
  1662. void AllocEngine::reclaimLeaseInDatabase(const LeasePtrType& lease,
  1663. const bool remove_lease,
  1664. const boost::function<void (const LeasePtrType&)>&
  1665. lease_update_fun) const {
  1666. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1667. // Reclaim the lease - depending on the configuration, set the
  1668. // expired-reclaimed state or simply remove it.
  1669. if (remove_lease) {
  1670. lease_mgr.deleteLease(lease->addr_);
  1671. } else if (!lease_update_fun.empty()) {
  1672. // Clear FQDN information as we have already sent the
  1673. // name change request to remove the DNS record.
  1674. lease->hostname_.clear();
  1675. lease->fqdn_fwd_ = false;
  1676. lease->fqdn_rev_ = false;
  1677. lease->state_ = Lease::STATE_EXPIRED_RECLAIMED;
  1678. lease_update_fun(lease);
  1679. } else {
  1680. return;
  1681. }
  1682. // Lease has been reclaimed.
  1683. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1684. ALLOC_ENGINE_LEASE_RECLAIMED)
  1685. .arg(lease->addr_.toText());
  1686. }
  1687. } // end of isc::dhcp namespace
  1688. } // end of isc namespace
  1689. // ##########################################################################
  1690. // # DHCPv4 lease allocation code starts here.
  1691. // ##########################################################################
  1692. namespace {
  1693. /// @brief Check if the specific address is reserved for another client.
  1694. ///
  1695. /// This function uses the HW address from the context to check if the
  1696. /// requested address (specified as first parameter) is reserved for
  1697. /// another client, i.e. client using a different HW address.
  1698. ///
  1699. /// @param address An address for which the function should check if
  1700. /// there is a reservation for the different client.
  1701. /// @param ctx Client context holding the data extracted from the
  1702. /// client's message.
  1703. ///
  1704. /// @return true if the address is reserved for another client.
  1705. bool
  1706. addressReserved(const IOAddress& address, const AllocEngine::ClientContext4& ctx) {
  1707. ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(), address);
  1708. HWAddrPtr host_hwaddr;
  1709. if (host) {
  1710. host_hwaddr = host->getHWAddress();
  1711. if (ctx.hwaddr_ && host_hwaddr) {
  1712. /// @todo Use the equality operators for HWAddr class.
  1713. /// Currently, this is impossible because the HostMgr uses the
  1714. /// HTYPE_ETHER type, whereas the unit tests may use other types
  1715. /// which HostMgr doesn't support yet.
  1716. return (host_hwaddr->hwaddr_ != ctx.hwaddr_->hwaddr_);
  1717. } else {
  1718. return (false);
  1719. }
  1720. }
  1721. return (false);
  1722. }
  1723. /// @brief Check if the context contains the reservation for the
  1724. /// IPv4 address.
  1725. ///
  1726. /// This convenience function checks if the context contains the reservation
  1727. /// for the IPv4 address. Note that some reservations may not assign a
  1728. /// static IPv4 address to the clients, but may rather reserve a hostname.
  1729. /// Allocation engine should check if the existing reservation is made
  1730. /// for the IPv4 address and if it is not, allocate the address from the
  1731. /// dynamic pool. The allocation engine uses this function to check if
  1732. /// the reservation is made for the IPv4 address.
  1733. ///
  1734. /// @param ctx Client context holding the data extracted from the
  1735. /// client's message.
  1736. ///
  1737. /// @return true if the context contains the reservation for the IPv4 address.
  1738. bool
  1739. hasAddressReservation(const AllocEngine::ClientContext4& ctx) {
  1740. return (ctx.host_ && !ctx.host_->getIPv4Reservation().isV4Zero());
  1741. }
  1742. /// @brief Finds existing lease in the database.
  1743. ///
  1744. /// This function searches for the lease in the database which belongs to the
  1745. /// client requesting allocation. If the client has supplied the client
  1746. /// identifier this identifier is used to look up the lease. If the lease is
  1747. /// not found using the client identifier, an additional lookup is performed
  1748. /// using the HW address, if supplied. If the lease is found using the HW
  1749. /// address, the function also checks if the lease belongs to the client, i.e.
  1750. /// there is no conflict between the client identifiers.
  1751. ///
  1752. /// @param ctx Context holding data extracted from the client's message,
  1753. /// including the HW address and client identifier.
  1754. /// @param [out] client_lease A pointer to the lease returned by this function
  1755. /// or null value if no has been lease found.
  1756. void findClientLease(const AllocEngine::ClientContext4& ctx, Lease4Ptr& client_lease) {
  1757. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1758. // If client identifier has been supplied, use it to lookup the lease. This
  1759. // search will return no lease if the client doesn't have any lease in the
  1760. // database or if the client didn't use client identifier to allocate the
  1761. // existing lease (this include cases when the server was explicitly
  1762. // configured to ignore client identifier).
  1763. if (ctx.clientid_) {
  1764. client_lease = lease_mgr.getLease4(*ctx.clientid_, ctx.subnet_->getID());
  1765. }
  1766. // If no lease found using the client identifier, try the lookup using
  1767. // the HW address.
  1768. if (!client_lease && ctx.hwaddr_) {
  1769. client_lease = lease_mgr.getLease4(*ctx.hwaddr_, ctx.subnet_->getID());
  1770. // This lookup may return the lease which has conflicting client
  1771. // identifier and thus is considered to belong to someone else.
  1772. // If this is the case, we need to toss the result and force the
  1773. // Allocation Engine to allocate another lease.
  1774. if (client_lease && !client_lease->belongsToClient(ctx.hwaddr_, ctx.clientid_)) {
  1775. client_lease.reset();
  1776. }
  1777. }
  1778. }
  1779. } // end of anonymous namespace
  1780. namespace isc {
  1781. namespace dhcp {
  1782. AllocEngine::ClientContext4::ClientContext4()
  1783. : subnet_(), clientid_(), hwaddr_(),
  1784. requested_address_(IOAddress::IPV4_ZERO_ADDRESS()),
  1785. fwd_dns_update_(false), rev_dns_update_(false),
  1786. hostname_(""), callout_handle_(), fake_allocation_(false),
  1787. old_lease_(), host_(), conflicting_lease_(), query_(),
  1788. host_identifiers_() {
  1789. }
  1790. AllocEngine::ClientContext4::ClientContext4(const Subnet4Ptr& subnet,
  1791. const ClientIdPtr& clientid,
  1792. const HWAddrPtr& hwaddr,
  1793. const asiolink::IOAddress& requested_addr,
  1794. const bool fwd_dns_update,
  1795. const bool rev_dns_update,
  1796. const std::string& hostname,
  1797. const bool fake_allocation)
  1798. : subnet_(subnet), clientid_(clientid), hwaddr_(hwaddr),
  1799. requested_address_(requested_addr),
  1800. fwd_dns_update_(fwd_dns_update), rev_dns_update_(rev_dns_update),
  1801. hostname_(hostname), callout_handle_(),
  1802. fake_allocation_(fake_allocation), old_lease_(), host_(),
  1803. host_identifiers_() {
  1804. // Initialize host identifiers.
  1805. if (hwaddr) {
  1806. addHostIdentifier(Host::IDENT_HWADDR, hwaddr->hwaddr_);
  1807. }
  1808. }
  1809. Lease4Ptr
  1810. AllocEngine::allocateLease4(ClientContext4& ctx) {
  1811. // The NULL pointer indicates that the old lease didn't exist. It may
  1812. // be later set to non NULL value if existing lease is found in the
  1813. // database.
  1814. ctx.old_lease_.reset();
  1815. Lease4Ptr new_lease;
  1816. try {
  1817. if (!ctx.subnet_) {
  1818. isc_throw(BadValue, "Can't allocate IPv4 address without subnet");
  1819. }
  1820. if (!ctx.hwaddr_) {
  1821. isc_throw(BadValue, "HWAddr must be defined");
  1822. }
  1823. new_lease = ctx.fake_allocation_ ? discoverLease4(ctx) : requestLease4(ctx);
  1824. } catch (const isc::Exception& e) {
  1825. // Some other error, return an empty lease.
  1826. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V4_ALLOC_ERROR)
  1827. .arg(ctx.query_->getLabel())
  1828. .arg(e.what());
  1829. }
  1830. return (new_lease);
  1831. }
  1832. void
  1833. AllocEngine::findReservation(ClientContext4& ctx) {
  1834. findReservationInternal(ctx, boost::bind(&HostMgr::get4,
  1835. &HostMgr::instance(),
  1836. _1, _2, _3, _4));
  1837. }
  1838. Lease4Ptr
  1839. AllocEngine::discoverLease4(AllocEngine::ClientContext4& ctx) {
  1840. // Find an existing lease for this client. This function will return true
  1841. // if there is a conflict with existing lease and the allocation should
  1842. // not be continued.
  1843. Lease4Ptr client_lease;
  1844. findClientLease(ctx, client_lease);
  1845. // new_lease will hold the pointer to the lease that we will offer to the
  1846. // caller.
  1847. Lease4Ptr new_lease;
  1848. // Check if there is a reservation for the client. If there is, we want to
  1849. // assign the reserved address, rather than any other one.
  1850. if (hasAddressReservation(ctx)) {
  1851. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1852. ALLOC_ENGINE_V4_DISCOVER_HR)
  1853. .arg(ctx.query_->getLabel())
  1854. .arg(ctx.host_->getIPv4Reservation().toText());
  1855. // If the client doesn't have a lease or the leased address is different
  1856. // than the reserved one then let's try to allocate the reserved address.
  1857. // Otherwise the address that the client has is the one for which it
  1858. // has a reservation, so just renew it.
  1859. if (!client_lease || (client_lease->addr_ != ctx.host_->getIPv4Reservation())) {
  1860. // The call below will return a pointer to the lease for the address
  1861. // reserved to this client, if the lease is available, i.e. is not
  1862. // currently assigned to any other client.
  1863. // Note that we don't remove the existing client's lease at this point
  1864. // because this is not a real allocation, we just offer what we can
  1865. // allocate in the DHCPREQUEST time.
  1866. new_lease = allocateOrReuseLease4(ctx.host_->getIPv4Reservation(), ctx);
  1867. if (!new_lease) {
  1868. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V4_DISCOVER_ADDRESS_CONFLICT)
  1869. .arg(ctx.query_->getLabel())
  1870. .arg(ctx.host_->getIPv4Reservation().toText())
  1871. .arg(ctx.conflicting_lease_ ? ctx.conflicting_lease_->toText() :
  1872. "(no lease info)");
  1873. }
  1874. } else {
  1875. new_lease = renewLease4(client_lease, ctx);
  1876. }
  1877. }
  1878. // Client does not have a reservation or the allocation of the reserved
  1879. // address has failed, probably because the reserved address is in use
  1880. // by another client. If the client has a lease, we will check if we can
  1881. // offer this lease to the client. The lease can't be offered in the
  1882. // situation when it is reserved for another client or when the address
  1883. // is not in the dynamic pool. The former may be the result of adding the
  1884. // new reservation for the address used by this client. The latter may
  1885. // be due to the client using the reserved out-of-the pool address, for
  1886. // which the reservation has just been removed.
  1887. if (!new_lease && client_lease &&
  1888. ctx.subnet_->inPool(Lease::TYPE_V4, client_lease->addr_) &&
  1889. !addressReserved(client_lease->addr_, ctx)) {
  1890. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1891. ALLOC_ENGINE_V4_OFFER_EXISTING_LEASE)
  1892. .arg(ctx.query_->getLabel());
  1893. new_lease = renewLease4(client_lease, ctx);
  1894. }
  1895. // The client doesn't have any lease or the lease can't be offered
  1896. // because it is either reserved for some other client or the
  1897. // address is not in the dynamic pool.
  1898. // Let's use the client's hint (requested IP address), if the client
  1899. // has provided it, and try to offer it. This address must not be
  1900. // reserved for another client, and must be in the range of the
  1901. // dynamic pool.
  1902. if (!new_lease && !ctx.requested_address_.isV4Zero() &&
  1903. ctx.subnet_->inPool(Lease::TYPE_V4, ctx.requested_address_) &&
  1904. !addressReserved(ctx.requested_address_, ctx)) {
  1905. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1906. ALLOC_ENGINE_V4_OFFER_REQUESTED_LEASE)
  1907. .arg(ctx.requested_address_.toText())
  1908. .arg(ctx.query_->getLabel());
  1909. new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx);
  1910. }
  1911. // The allocation engine failed to allocate all of the candidate
  1912. // addresses. We will now use the allocator to pick the address
  1913. // from the dynamic pool.
  1914. if (!new_lease) {
  1915. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1916. ALLOC_ENGINE_V4_OFFER_NEW_LEASE)
  1917. .arg(ctx.query_->getLabel());
  1918. new_lease = allocateUnreservedLease4(ctx);
  1919. }
  1920. // Some of the methods like reuseExpiredLease4 may set the old lease to point
  1921. // to the lease which they remove/override. If it is not set, but we have
  1922. // found that the client has the lease the client's lease is the one
  1923. // to return as an old lease.
  1924. if (!ctx.old_lease_ && client_lease) {
  1925. ctx.old_lease_ = client_lease;
  1926. }
  1927. return (new_lease);
  1928. }
  1929. Lease4Ptr
  1930. AllocEngine::requestLease4(AllocEngine::ClientContext4& ctx) {
  1931. // Find an existing lease for this client. This function will return true
  1932. // if there is a conflict with existing lease and the allocation should
  1933. // not be continued.
  1934. Lease4Ptr client_lease;
  1935. findClientLease(ctx, client_lease);
  1936. // Obtain the sole instance of the LeaseMgr.
  1937. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1938. // When the client sends the DHCPREQUEST, it should always specify the
  1939. // address which it is requesting or renewing. That is, the client should
  1940. // either use the requested IP address option or set the ciaddr. However,
  1941. // we try to be liberal and allow the clients to not specify an address
  1942. // in which case the allocation engine will pick a suitable address
  1943. // for the client.
  1944. if (!ctx.requested_address_.isV4Zero()) {
  1945. // If the client has specified an address, make sure this address
  1946. // is not reserved for another client. If it is, stop here because
  1947. // we can't allocate this address.
  1948. if (addressReserved(ctx.requested_address_, ctx)) {
  1949. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1950. ALLOC_ENGINE_V4_REQUEST_ADDRESS_RESERVED)
  1951. .arg(ctx.query_->getLabel())
  1952. .arg(ctx.requested_address_.toText());
  1953. return (Lease4Ptr());
  1954. }
  1955. } else if (hasAddressReservation(ctx)) {
  1956. // The client hasn't specified an address to allocate, so the
  1957. // allocation engine needs to find an appropriate address.
  1958. // If there is a reservation for the client, let's try to
  1959. // allocate the reserved address.
  1960. ctx.requested_address_ = ctx.host_->getIPv4Reservation();
  1961. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1962. ALLOC_ENGINE_V4_REQUEST_USE_HR)
  1963. .arg(ctx.query_->getLabel())
  1964. .arg(ctx.requested_address_.toText());
  1965. }
  1966. if (!ctx.requested_address_.isV4Zero()) {
  1967. // There is a specific address to be allocated. Let's find out if
  1968. // the address is in use.
  1969. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(ctx.requested_address_);
  1970. // If the address is in use (allocated and not expired), we check
  1971. // if the address is in use by our client or another client.
  1972. // If it is in use by another client, the address can't be
  1973. // allocated.
  1974. if (existing && !existing->expired() &&
  1975. !existing->belongsToClient(ctx.hwaddr_, ctx.clientid_)) {
  1976. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1977. ALLOC_ENGINE_V4_REQUEST_IN_USE)
  1978. .arg(ctx.query_->getLabel())
  1979. .arg(ctx.requested_address_.toText());
  1980. return (Lease4Ptr());
  1981. }
  1982. // If the client has a reservation but it is requesting a different
  1983. // address it is possible that the client was offered this different
  1984. // address because the reserved address is in use. We will have to
  1985. // check if the address is in use.
  1986. if (hasAddressReservation(ctx) &&
  1987. (ctx.host_->getIPv4Reservation() != ctx.requested_address_)) {
  1988. existing = LeaseMgrFactory::instance().getLease4(ctx.host_->getIPv4Reservation());
  1989. // If the reserved address is not in use, i.e. the lease doesn't
  1990. // exist or is expired, and the client is requesting a different
  1991. // address, return NULL. The client should go back to the
  1992. // DHCPDISCOVER and the reserved address will be offered.
  1993. if (!existing || existing->expired()) {
  1994. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1995. ALLOC_ENGINE_V4_REQUEST_INVALID)
  1996. .arg(ctx.query_->getLabel())
  1997. .arg(ctx.host_->getIPv4Reservation().toText())
  1998. .arg(ctx.requested_address_.toText());
  1999. return (Lease4Ptr());
  2000. }
  2001. }
  2002. // The use of the out-of-pool addresses is only allowed when the requested
  2003. // address is reserved for the client. If the address is not reserved one
  2004. // and it doesn't belong to the dynamic pool, do not allocate it.
  2005. if ((!hasAddressReservation(ctx) ||
  2006. (ctx.host_->getIPv4Reservation() != ctx.requested_address_)) &&
  2007. !ctx.subnet_->inPool(Lease4::TYPE_V4, ctx.requested_address_)) {
  2008. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  2009. ALLOC_ENGINE_V4_REQUEST_OUT_OF_POOL)
  2010. .arg(ctx.query_->getLabel())
  2011. .arg(ctx.requested_address_);
  2012. return (Lease4Ptr());
  2013. }
  2014. }
  2015. // We have gone through all the checks, so we can now allocate the address
  2016. // for the client.
  2017. // If the client is requesting an address which is assigned to the client
  2018. // let's just renew this address. Also, renew this address if the client
  2019. // doesn't request any specific address.
  2020. if (client_lease) {
  2021. if ((client_lease->addr_ == ctx.requested_address_) ||
  2022. ctx.requested_address_.isV4Zero()) {
  2023. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  2024. ALLOC_ENGINE_V4_REQUEST_EXTEND_LEASE)
  2025. .arg(ctx.query_->getLabel())
  2026. .arg(ctx.requested_address_);
  2027. return (renewLease4(client_lease, ctx));
  2028. }
  2029. }
  2030. // new_lease will hold the pointer to the allocated lease if we allocate
  2031. // successfully.
  2032. Lease4Ptr new_lease;
  2033. // The client doesn't have the lease or it is requesting an address
  2034. // which it doesn't have. Let's try to allocate the requested address.
  2035. if (!ctx.requested_address_.isV4Zero()) {
  2036. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  2037. ALLOC_ENGINE_V4_REQUEST_ALLOC_REQUESTED)
  2038. .arg(ctx.query_->getLabel())
  2039. .arg(ctx.requested_address_.toText());
  2040. // The call below will return a pointer to the lease allocated
  2041. // for the client if there is no lease for the requested address,
  2042. // or the existing lease has expired. If the allocation fails,
  2043. // e.g. because the lease is in use, we will return NULL to
  2044. // indicate that we were unable to allocate the lease.
  2045. new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx);
  2046. } else {
  2047. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  2048. ALLOC_ENGINE_V4_REQUEST_PICK_ADDRESS)
  2049. .arg(ctx.query_->getLabel());
  2050. // We will only get here if the client didn't specify which
  2051. // address it wanted to be allocated. The allocation engine will
  2052. // to pick the address from the dynamic pool.
  2053. new_lease = allocateUnreservedLease4(ctx);
  2054. }
  2055. // If we allocated the lease for the client, but the client already had a
  2056. // lease, we will need to return the pointer to the previous lease and
  2057. // the previous lease needs to be removed from the lease database.
  2058. if (new_lease && client_lease) {
  2059. ctx.old_lease_ = Lease4Ptr(new Lease4(*client_lease));
  2060. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  2061. ALLOC_ENGINE_V4_REQUEST_REMOVE_LEASE)
  2062. .arg(ctx.query_->getLabel())
  2063. .arg(client_lease->addr_.toText());
  2064. lease_mgr.deleteLease(client_lease->addr_);
  2065. // Need to decrease statistic for assigned addresses.
  2066. StatsMgr::instance().addValue(
  2067. StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-addresses"),
  2068. static_cast<int64_t>(-1));
  2069. }
  2070. // Return the allocated lease or NULL pointer if allocation was
  2071. // unsuccessful.
  2072. return (new_lease);
  2073. }
  2074. Lease4Ptr
  2075. AllocEngine::createLease4(const ClientContext4& ctx, const IOAddress& addr) {
  2076. if (!ctx.hwaddr_) {
  2077. isc_throw(BadValue, "Can't create a lease with NULL HW address");
  2078. }
  2079. if (!ctx.subnet_) {
  2080. isc_throw(BadValue, "Can't create a lease without a subnet");
  2081. }
  2082. time_t now = time(NULL);
  2083. // @todo: remove this kludge after ticket #2590 is implemented
  2084. std::vector<uint8_t> local_copy;
  2085. if (ctx.clientid_) {
  2086. local_copy = ctx.clientid_->getDuid();
  2087. }
  2088. const uint8_t* local_copy0 = local_copy.empty() ? 0 : &local_copy[0];
  2089. Lease4Ptr lease(new Lease4(addr, ctx.hwaddr_, local_copy0, local_copy.size(),
  2090. ctx.subnet_->getValid(), ctx.subnet_->getT1(),
  2091. ctx.subnet_->getT2(),
  2092. now, ctx.subnet_->getID()));
  2093. // Set FQDN specific lease parameters.
  2094. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  2095. lease->fqdn_rev_ = ctx.rev_dns_update_;
  2096. lease->hostname_ = ctx.hostname_;
  2097. // Let's execute all callouts registered for lease4_select
  2098. if (ctx.callout_handle_ &&
  2099. HooksManager::getHooksManager().calloutsPresent(hook_index_lease4_select_)) {
  2100. // Delete all previous arguments
  2101. ctx.callout_handle_->deleteAllArguments();
  2102. // Enable copying options from the packet within hook library.
  2103. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
  2104. // Pass necessary arguments
  2105. // Pass the original client query
  2106. ctx.callout_handle_->setArgument("query4", ctx.query_);
  2107. // Subnet from which we do the allocation (That's as far as we can go
  2108. // with using SubnetPtr to point to Subnet4 object. Users should not
  2109. // be confused with dynamic_pointer_casts. They should get a concrete
  2110. // pointer (Subnet4Ptr) pointing to a Subnet4 object.
  2111. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  2112. ctx.callout_handle_->setArgument("subnet4", subnet4);
  2113. // Is this solicit (fake = true) or request (fake = false)
  2114. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  2115. // Pass the intended lease as well
  2116. ctx.callout_handle_->setArgument("lease4", lease);
  2117. // This is the first callout, so no need to clear any arguments
  2118. HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
  2119. // Callouts decided to skip the action. This means that the lease is not
  2120. // assigned, so the client will get NoAddrAvail as a result. The lease
  2121. // won't be inserted into the database.
  2122. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  2123. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  2124. return (Lease4Ptr());
  2125. }
  2126. // Let's use whatever callout returned. Hopefully it is the same lease
  2127. // we handled to it.
  2128. ctx.callout_handle_->getArgument("lease4", lease);
  2129. }
  2130. if (!ctx.fake_allocation_) {
  2131. // That is a real (REQUEST) allocation
  2132. bool status = LeaseMgrFactory::instance().addLease(lease);
  2133. if (status) {
  2134. // The lease insertion succeeded, let's bump up the statistic.
  2135. StatsMgr::instance().addValue(
  2136. StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-addresses"),
  2137. static_cast<int64_t>(1));
  2138. return (lease);
  2139. } else {
  2140. // One of many failures with LeaseMgr (e.g. lost connection to the
  2141. // database, database failed etc.). One notable case for that
  2142. // is that we are working in multi-process mode and we lost a race
  2143. // (some other process got that address first)
  2144. return (Lease4Ptr());
  2145. }
  2146. } else {
  2147. // That is only fake (DISCOVER) allocation
  2148. // It is for OFFER only. We should not insert the lease into LeaseMgr,
  2149. // but rather check that we could have inserted it.
  2150. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(addr);
  2151. if (!existing) {
  2152. return (lease);
  2153. } else {
  2154. return (Lease4Ptr());
  2155. }
  2156. }
  2157. }
  2158. Lease4Ptr
  2159. AllocEngine::renewLease4(const Lease4Ptr& lease,
  2160. AllocEngine::ClientContext4& ctx) {
  2161. if (!lease) {
  2162. isc_throw(BadValue, "null lease specified for renewLease4");
  2163. }
  2164. // Let's keep the old data. This is essential if we are using memfile
  2165. // (the lease returned points directly to the lease4 object in the database)
  2166. // We'll need it if we want to skip update (i.e. roll back renewal)
  2167. /// @todo: remove this once #3083 is implemented
  2168. Lease4 old_values = *lease;
  2169. ctx.old_lease_.reset(new Lease4(old_values));
  2170. // Update the lease with the information from the context.
  2171. updateLease4Information(lease, ctx);
  2172. if (!ctx.fake_allocation_) {
  2173. // If the lease is expired we have to reclaim it before
  2174. // re-assigning it to the client. The lease reclamation
  2175. // involves execution of hooks and DNS update.
  2176. if (ctx.old_lease_->expired()) {
  2177. reclaimExpiredLease(ctx.old_lease_, ctx.callout_handle_);
  2178. lease->state_ = Lease::STATE_DEFAULT;
  2179. } else if (!lease->hasIdenticalFqdn(*ctx.old_lease_)) {
  2180. // The lease is not expired but the FQDN information has
  2181. // changed. So, we have to remove the previous DNS entry.
  2182. queueNCR(CHG_REMOVE, ctx.old_lease_);
  2183. }
  2184. }
  2185. bool skip = false;
  2186. // Execute all callouts registered for lease4_renew.
  2187. if (HooksManager::getHooksManager().
  2188. calloutsPresent(Hooks.hook_index_lease4_renew_)) {
  2189. // Delete all previous arguments
  2190. ctx.callout_handle_->deleteAllArguments();
  2191. // Enable copying options from the packet within hook library.
  2192. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
  2193. // Subnet from which we do the allocation. Convert the general subnet
  2194. // pointer to a pointer to a Subnet4. Note that because we are using
  2195. // boost smart pointers here, we need to do the cast using the boost
  2196. // version of dynamic_pointer_cast.
  2197. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  2198. // Pass the parameters
  2199. ctx.callout_handle_->setArgument("query4", ctx.query_);
  2200. ctx.callout_handle_->setArgument("subnet4", subnet4);
  2201. ctx.callout_handle_->setArgument("clientid", ctx.clientid_);
  2202. ctx.callout_handle_->setArgument("hwaddr", ctx.hwaddr_);
  2203. // Pass the lease to be updated
  2204. ctx.callout_handle_->setArgument("lease4", lease);
  2205. // Call all installed callouts
  2206. HooksManager::callCallouts(Hooks.hook_index_lease4_renew_,
  2207. *ctx.callout_handle_);
  2208. // Callouts decided to skip the next processing step. The next
  2209. // processing step would actually renew the lease, so skip at this
  2210. // stage means "keep the old lease as it is".
  2211. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  2212. skip = true;
  2213. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  2214. DHCPSRV_HOOK_LEASE4_RENEW_SKIP);
  2215. }
  2216. /// @todo: Add support for DROP status
  2217. }
  2218. if (!ctx.fake_allocation_ && !skip) {
  2219. // for REQUEST we do update the lease
  2220. LeaseMgrFactory::instance().updateLease4(lease);
  2221. }
  2222. if (skip) {
  2223. // Rollback changes (really useful only for memfile)
  2224. /// @todo: remove this once #3083 is implemented
  2225. *lease = old_values;
  2226. }
  2227. return (lease);
  2228. }
  2229. Lease4Ptr
  2230. AllocEngine::reuseExpiredLease4(Lease4Ptr& expired,
  2231. AllocEngine::ClientContext4& ctx) {
  2232. if (!expired) {
  2233. isc_throw(BadValue, "null lease specified for reuseExpiredLease");
  2234. }
  2235. if (!ctx.subnet_) {
  2236. isc_throw(BadValue, "null subnet specified for the reuseExpiredLease");
  2237. }
  2238. if (!ctx.fake_allocation_) {
  2239. // The expired lease needs to be reclaimed before it can be reused.
  2240. // This includes declined leases for which probation period has
  2241. // elapsed.
  2242. reclaimExpiredLease(expired, ctx.callout_handle_);
  2243. expired->state_ = Lease::STATE_DEFAULT;
  2244. }
  2245. updateLease4Information(expired, ctx);
  2246. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA,
  2247. ALLOC_ENGINE_V4_REUSE_EXPIRED_LEASE_DATA)
  2248. .arg(ctx.query_->getLabel())
  2249. .arg(expired->toText());
  2250. // Let's execute all callouts registered for lease4_select
  2251. if (ctx.callout_handle_ && HooksManager::getHooksManager()
  2252. .calloutsPresent(hook_index_lease4_select_)) {
  2253. // Enable copying options from the packet within hook library.
  2254. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
  2255. // Delete all previous arguments
  2256. ctx.callout_handle_->deleteAllArguments();
  2257. // Pass necessary arguments
  2258. // Pass the original client query
  2259. ctx.callout_handle_->setArgument("query4", ctx.query_);
  2260. // Subnet from which we do the allocation. Convert the general subnet
  2261. // pointer to a pointer to a Subnet4. Note that because we are using
  2262. // boost smart pointers here, we need to do the cast using the boost
  2263. // version of dynamic_pointer_cast.
  2264. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  2265. ctx.callout_handle_->setArgument("subnet4", subnet4);
  2266. // Is this solicit (fake = true) or request (fake = false)
  2267. ctx.callout_handle_->setArgument("fake_allocation",
  2268. ctx.fake_allocation_);
  2269. // The lease that will be assigned to a client
  2270. ctx.callout_handle_->setArgument("lease4", expired);
  2271. // Call the callouts
  2272. HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
  2273. // Callouts decided to skip the action. This means that the lease is not
  2274. // assigned, so the client will get NoAddrAvail as a result. The lease
  2275. // won't be inserted into the database.
  2276. if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  2277. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  2278. DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  2279. return (Lease4Ptr());
  2280. }
  2281. /// @todo: add support for DROP
  2282. // Let's use whatever callout returned. Hopefully it is the same lease
  2283. // we handed to it.
  2284. ctx.callout_handle_->getArgument("lease4", expired);
  2285. }
  2286. if (!ctx.fake_allocation_) {
  2287. // for REQUEST we do update the lease
  2288. LeaseMgrFactory::instance().updateLease4(expired);
  2289. }
  2290. // We do nothing for SOLICIT. We'll just update database when
  2291. // the client gets back to us with REQUEST message.
  2292. // it's not really expired at this stage anymore - let's return it as
  2293. // an updated lease
  2294. return (expired);
  2295. }
  2296. Lease4Ptr
  2297. AllocEngine::allocateOrReuseLease4(const IOAddress& candidate, ClientContext4& ctx) {
  2298. ctx.conflicting_lease_.reset();
  2299. Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
  2300. if (exist_lease) {
  2301. if (exist_lease->expired()) {
  2302. ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
  2303. return (reuseExpiredLease4(exist_lease, ctx));
  2304. } else {
  2305. // If there is a lease and it is not expired, pass this lease back
  2306. // to the caller in the context. The caller may need to know
  2307. // which lease we're conflicting with.
  2308. ctx.conflicting_lease_ = exist_lease;
  2309. }
  2310. } else {
  2311. return (createLease4(ctx, candidate));
  2312. }
  2313. return (Lease4Ptr());
  2314. }
  2315. Lease4Ptr
  2316. AllocEngine::allocateUnreservedLease4(ClientContext4& ctx) {
  2317. Lease4Ptr new_lease;
  2318. AllocatorPtr allocator = getAllocator(Lease::TYPE_V4);
  2319. const uint64_t max_attempts = (attempts_ > 0 ? attempts_ :
  2320. ctx.subnet_->getPoolCapacity(Lease::TYPE_V4));
  2321. for (uint64_t i = 0; i < max_attempts; ++i) {
  2322. IOAddress candidate = allocator->pickAddress(ctx.subnet_, ctx.clientid_,
  2323. ctx.requested_address_);
  2324. // If address is not reserved for another client, try to allocate it.
  2325. if (!addressReserved(candidate, ctx)) {
  2326. // The call below will return the non-NULL pointer if we
  2327. // successfully allocate this lease. This means that the
  2328. // address is not in use by another client.
  2329. new_lease = allocateOrReuseLease4(candidate, ctx);
  2330. if (new_lease) {
  2331. return (new_lease);
  2332. }
  2333. }
  2334. }
  2335. // Unable to allocate an address, return an empty lease.
  2336. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V4_ALLOC_FAIL)
  2337. .arg(ctx.query_->getLabel())
  2338. .arg(max_attempts);
  2339. return (new_lease);
  2340. }
  2341. void
  2342. AllocEngine::updateLease4Information(const Lease4Ptr& lease,
  2343. AllocEngine::ClientContext4& ctx) const {
  2344. lease->subnet_id_ = ctx.subnet_->getID();
  2345. lease->hwaddr_ = ctx.hwaddr_;
  2346. lease->client_id_ = ctx.clientid_;
  2347. lease->cltt_ = time(NULL);
  2348. lease->t1_ = ctx.subnet_->getT1();
  2349. lease->t2_ = ctx.subnet_->getT2();
  2350. lease->valid_lft_ = ctx.subnet_->getValid();
  2351. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  2352. lease->fqdn_rev_ = ctx.rev_dns_update_;
  2353. lease->hostname_ = ctx.hostname_;
  2354. }
  2355. bool
  2356. AllocEngine::conditionalExtendLifetime(Lease& lease) const {
  2357. lease.cltt_ = time(NULL);
  2358. return (true);
  2359. }
  2360. }; // end of isc::dhcp namespace
  2361. }; // end of isc namespace