alloc_engine.cc 110 KB

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