alloc_engine.cc 111 KB

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