alloc_engine.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. // Copyright (C) 2012-2013 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <dhcpsrv/alloc_engine.h>
  15. #include <dhcpsrv/dhcpsrv_log.h>
  16. #include <dhcpsrv/lease_mgr_factory.h>
  17. #include <cstring>
  18. #include <vector>
  19. #include <string.h>
  20. using namespace isc::asiolink;
  21. namespace isc {
  22. namespace dhcp {
  23. AllocEngine::IterativeAllocator::IterativeAllocator()
  24. :Allocator() {
  25. }
  26. isc::asiolink::IOAddress
  27. AllocEngine::IterativeAllocator::increaseAddress(const isc::asiolink::IOAddress& addr) {
  28. // Get a buffer holding an address.
  29. const std::vector<uint8_t>& vec = addr.toBytes();
  30. // Get the address length.
  31. const int len = vec.size();
  32. // Since the same array will be used to hold the IPv4 and IPv6
  33. // address we have to make sure that the size of the array
  34. // we allocate will work for both types of address.
  35. BOOST_STATIC_ASSERT(V4ADDRESS_LEN <= V6ADDRESS_LEN);
  36. uint8_t packed[V6ADDRESS_LEN];
  37. // Copy the address. It can be either V4 or V6.
  38. std::memcpy(packed, &vec[0], len);
  39. // Start increasing the least significant byte
  40. for (int i = len - 1; i >= 0; --i) {
  41. ++packed[i];
  42. // if we haven't overflowed (0xff -> 0x0), than we are done
  43. if (packed[i] != 0) {
  44. break;
  45. }
  46. }
  47. return (IOAddress::fromBytes(addr.getFamily(), packed));
  48. }
  49. isc::asiolink::IOAddress
  50. AllocEngine::IterativeAllocator::pickAddress(const SubnetPtr& subnet,
  51. const DuidPtr&,
  52. const IOAddress&) {
  53. // Let's get the last allocated address. It is usually set correctly,
  54. // but there are times when it won't be (like after removing a pool or
  55. // perhaps restaring the server).
  56. IOAddress last = subnet->getLastAllocated();
  57. const PoolCollection& pools = subnet->getPools();
  58. if (pools.empty()) {
  59. isc_throw(AllocFailed, "No pools defined in selected subnet");
  60. }
  61. // first we need to find a pool the last address belongs to.
  62. PoolCollection::const_iterator it;
  63. for (it = pools.begin(); it != pools.end(); ++it) {
  64. if ((*it)->inRange(last)) {
  65. break;
  66. }
  67. }
  68. // last one was bogus for one of several reasons:
  69. // - we just booted up and that's the first address we're allocating
  70. // - a subnet was removed or other reconfiguration just completed
  71. // - perhaps allocation algorithm was changed
  72. if (it == pools.end()) {
  73. // ok to access first element directly. We checked that pools is non-empty
  74. IOAddress next = pools[0]->getFirstAddress();
  75. subnet->setLastAllocated(next);
  76. return (next);
  77. }
  78. // Ok, we have a pool that the last address belonged to, let's use it.
  79. IOAddress next = increaseAddress(last); // basically addr++
  80. if ((*it)->inRange(next)) {
  81. // the next one is in the pool as well, so we haven't hit pool boundary yet
  82. subnet->setLastAllocated(next);
  83. return (next);
  84. }
  85. // We hit pool boundary, let's try to jump to the next pool and try again
  86. ++it;
  87. if (it == pools.end()) {
  88. // Really out of luck today. That was the last pool. Let's rewind
  89. // to the beginning.
  90. next = pools[0]->getFirstAddress();
  91. subnet->setLastAllocated(next);
  92. return (next);
  93. }
  94. // there is a next pool, let's try first adddress from it
  95. next = (*it)->getFirstAddress();
  96. subnet->setLastAllocated(next);
  97. return (next);
  98. }
  99. AllocEngine::HashedAllocator::HashedAllocator()
  100. :Allocator() {
  101. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  102. }
  103. isc::asiolink::IOAddress
  104. AllocEngine::HashedAllocator::pickAddress(const SubnetPtr&,
  105. const DuidPtr&,
  106. const IOAddress&) {
  107. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  108. }
  109. AllocEngine::RandomAllocator::RandomAllocator()
  110. :Allocator() {
  111. isc_throw(NotImplemented, "Random allocator is not implemented");
  112. }
  113. isc::asiolink::IOAddress
  114. AllocEngine::RandomAllocator::pickAddress(const SubnetPtr&,
  115. const DuidPtr&,
  116. const IOAddress&) {
  117. isc_throw(NotImplemented, "Random allocator is not implemented");
  118. }
  119. AllocEngine::AllocEngine(AllocType engine_type, unsigned int attempts)
  120. :attempts_(attempts) {
  121. switch (engine_type) {
  122. case ALLOC_ITERATIVE:
  123. allocator_ = boost::shared_ptr<Allocator>(new IterativeAllocator());
  124. break;
  125. case ALLOC_HASHED:
  126. allocator_ = boost::shared_ptr<Allocator>(new HashedAllocator());
  127. break;
  128. case ALLOC_RANDOM:
  129. allocator_ = boost::shared_ptr<Allocator>(new RandomAllocator());
  130. break;
  131. default:
  132. isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
  133. }
  134. }
  135. Lease6Ptr
  136. AllocEngine::allocateAddress6(const Subnet6Ptr& subnet,
  137. const DuidPtr& duid,
  138. uint32_t iaid,
  139. const IOAddress& hint,
  140. bool fake_allocation /* = false */ ) {
  141. try {
  142. // That check is not necessary. We create allocator in AllocEngine
  143. // constructor
  144. if (!allocator_) {
  145. isc_throw(InvalidOperation, "No allocator selected");
  146. }
  147. // check if there's existing lease for that subnet/duid/iaid combination.
  148. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(*duid, iaid, subnet->getID());
  149. if (existing) {
  150. // we have a lease already. This is a returning client, probably after
  151. // his reboot.
  152. return (existing);
  153. }
  154. // check if the hint is in pool and is available
  155. if (subnet->inPool(hint)) {
  156. existing = LeaseMgrFactory::instance().getLease6(hint);
  157. if (!existing) {
  158. /// @todo: check if the hint is reserved once we have host support
  159. /// implemented
  160. // the hint is valid and not currently used, let's create a lease for it
  161. Lease6Ptr lease = createLease6(subnet, duid, iaid, hint, fake_allocation);
  162. // It can happen that the lease allocation failed (we could have lost
  163. // the race condition. That means that the hint is lo longer usable and
  164. // we need to continue the regular allocation path.
  165. if (lease) {
  166. return (lease);
  167. }
  168. } else {
  169. if (existing->expired()) {
  170. return (reuseExpiredLease(existing, subnet, duid, iaid,
  171. fake_allocation));
  172. }
  173. }
  174. }
  175. // Hint is in the pool but is not available. Search the pool until first of
  176. // the following occurs:
  177. // - we find a free address
  178. // - we find an address for which the lease has expired
  179. // - we exhaust number of tries
  180. //
  181. // @todo: Current code does not handle pool exhaustion well. It will be
  182. // improved. Current problems:
  183. // 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
  184. // 10 addresses), we will iterate over it 100 times before giving up
  185. // 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
  186. // 3. the whole concept of infinite attempts is just asking for infinite loop
  187. // We may consider some form or reference counting (this pool has X addresses
  188. // left), but this has one major problem. We exactly control allocation
  189. // moment, but we currently do not control expiration time at all
  190. unsigned int i = attempts_;
  191. do {
  192. IOAddress candidate = allocator_->pickAddress(subnet, duid, hint);
  193. /// @todo: check if the address is reserved once we have host support
  194. /// implemented
  195. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(candidate);
  196. if (!existing) {
  197. // there's no existing lease for selected candidate, so it is
  198. // free. Let's allocate it.
  199. Lease6Ptr lease = createLease6(subnet, duid, iaid, candidate,
  200. fake_allocation);
  201. if (lease) {
  202. return (lease);
  203. }
  204. // Although the address was free just microseconds ago, it may have
  205. // been taken just now. If the lease insertion fails, we continue
  206. // allocation attempts.
  207. } else {
  208. if (existing->expired()) {
  209. return (reuseExpiredLease(existing, subnet, duid, iaid,
  210. fake_allocation));
  211. }
  212. }
  213. // Continue trying allocation until we run out of attempts
  214. // (or attempts are set to 0, which means infinite)
  215. --i;
  216. } while ((i > 0) || !attempts_);
  217. // Unable to allocate an address, return an empty lease.
  218. LOG_WARN(dhcpsrv_logger, DHCPSRV_ADDRESS6_ALLOC_FAIL).arg(attempts_);
  219. } catch (const isc::Exception& e) {
  220. // Some other error, return an empty lease.
  221. LOG_ERROR(dhcpsrv_logger, DHCPSRV_ADDRESS6_ALLOC_ERROR).arg(e.what());
  222. }
  223. return (Lease6Ptr());
  224. }
  225. Lease4Ptr
  226. AllocEngine::allocateAddress4(const SubnetPtr& subnet,
  227. const ClientIdPtr& clientid,
  228. const HWAddrPtr& hwaddr,
  229. const IOAddress& hint,
  230. bool fake_allocation /* = false */ ) {
  231. try {
  232. // Allocator is always created in AllocEngine constructor and there is
  233. // currently no other way to set it, so that check is not really necessary.
  234. if (!allocator_) {
  235. isc_throw(InvalidOperation, "No allocator selected");
  236. }
  237. // Check if there's existing lease for that subnet/clientid/hwaddr combination.
  238. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(hwaddr->hwaddr_, subnet->getID());
  239. if (existing) {
  240. // We have a lease already. This is a returning client, probably after
  241. // its reboot.
  242. existing = renewLease4(subnet, clientid, hwaddr, existing, fake_allocation);
  243. if (existing) {
  244. return (existing);
  245. }
  246. // If renewal failed (e.g. the lease no longer matches current configuration)
  247. // let's continue the allocation process
  248. }
  249. if (clientid) {
  250. existing = LeaseMgrFactory::instance().getLease4(*clientid, subnet->getID());
  251. if (existing) {
  252. // we have a lease already. This is a returning client, probably after
  253. // its reboot.
  254. existing = renewLease4(subnet, clientid, hwaddr, existing, fake_allocation);
  255. // @todo: produce a warning. We haven't found him using MAC address, but
  256. // we found him using client-id
  257. if (existing) {
  258. return (existing);
  259. }
  260. }
  261. }
  262. // check if the hint is in pool and is available
  263. if (subnet->inPool(hint)) {
  264. existing = LeaseMgrFactory::instance().getLease4(hint);
  265. if (!existing) {
  266. /// @todo: Check if the hint is reserved once we have host support
  267. /// implemented
  268. // The hint is valid and not currently used, let's create a lease for it
  269. Lease4Ptr lease = createLease4(subnet, clientid, hwaddr, hint, fake_allocation);
  270. // It can happen that the lease allocation failed (we could have lost
  271. // the race condition. That means that the hint is lo longer usable and
  272. // we need to continue the regular allocation path.
  273. if (lease) {
  274. return (lease);
  275. }
  276. } else {
  277. if (existing->expired()) {
  278. return (reuseExpiredLease(existing, subnet, clientid, hwaddr,
  279. fake_allocation));
  280. }
  281. }
  282. }
  283. // Hint is in the pool but is not available. Search the pool until first of
  284. // the following occurs:
  285. // - we find a free address
  286. // - we find an address for which the lease has expired
  287. // - we exhaust the number of tries
  288. //
  289. // @todo: Current code does not handle pool exhaustion well. It will be
  290. // improved. Current problems:
  291. // 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
  292. // 10 addresses), we will iterate over it 100 times before giving up
  293. // 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
  294. // 3. the whole concept of infinite attempts is just asking for infinite loop
  295. // We may consider some form or reference counting (this pool has X addresses
  296. // left), but this has one major problem. We exactly control allocation
  297. // moment, but we currently do not control expiration time at all
  298. unsigned int i = attempts_;
  299. do {
  300. IOAddress candidate = allocator_->pickAddress(subnet, clientid, hint);
  301. /// @todo: check if the address is reserved once we have host support
  302. /// implemented
  303. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(candidate);
  304. if (!existing) {
  305. // there's no existing lease for selected candidate, so it is
  306. // free. Let's allocate it.
  307. Lease4Ptr lease = createLease4(subnet, clientid, hwaddr, candidate,
  308. fake_allocation);
  309. if (lease) {
  310. return (lease);
  311. }
  312. // Although the address was free just microseconds ago, it may have
  313. // been taken just now. If the lease insertion fails, we continue
  314. // allocation attempts.
  315. } else {
  316. if (existing->expired()) {
  317. return (reuseExpiredLease(existing, subnet, clientid, hwaddr,
  318. fake_allocation));
  319. }
  320. }
  321. // Continue trying allocation until we run out of attempts
  322. // (or attempts are set to 0, which means infinite)
  323. --i;
  324. } while ((i > 0) || !attempts_);
  325. // Unable to allocate an address, return an empty lease.
  326. LOG_WARN(dhcpsrv_logger, DHCPSRV_ADDRESS4_ALLOC_FAIL).arg(attempts_);
  327. } catch (const isc::Exception& e) {
  328. // Some other error, return an empty lease.
  329. LOG_ERROR(dhcpsrv_logger, DHCPSRV_ADDRESS4_ALLOC_ERROR).arg(e.what());
  330. }
  331. return (Lease4Ptr());
  332. }
  333. Lease4Ptr AllocEngine::renewLease4(const SubnetPtr& subnet,
  334. const ClientIdPtr& clientid,
  335. const HWAddrPtr& hwaddr,
  336. const Lease4Ptr& lease,
  337. bool fake_allocation /* = false */) {
  338. lease->subnet_id_ = subnet->getID();
  339. lease->hwaddr_ = hwaddr->hwaddr_;
  340. lease->client_id_ = clientid;
  341. lease->cltt_ = time(NULL);
  342. lease->t1_ = subnet->getT1();
  343. lease->t2_ = subnet->getT2();
  344. lease->valid_lft_ = subnet->getValid();
  345. if (!fake_allocation) {
  346. // for REQUEST we do update the lease
  347. LeaseMgrFactory::instance().updateLease4(lease);
  348. }
  349. return (lease);
  350. }
  351. Lease6Ptr AllocEngine::reuseExpiredLease(Lease6Ptr& expired,
  352. const Subnet6Ptr& subnet,
  353. const DuidPtr& duid,
  354. uint32_t iaid,
  355. bool fake_allocation /*= false */ ) {
  356. if (!expired->expired()) {
  357. isc_throw(BadValue, "Attempt to recycle lease that is still valid");
  358. }
  359. // address, lease type and prefixlen (0) stay the same
  360. expired->iaid_ = iaid;
  361. expired->duid_ = duid;
  362. expired->preferred_lft_ = subnet->getPreferred();
  363. expired->valid_lft_ = subnet->getValid();
  364. expired->t1_ = subnet->getT1();
  365. expired->t2_ = subnet->getT2();
  366. expired->cltt_ = time(NULL);
  367. expired->subnet_id_ = subnet->getID();
  368. expired->fixed_ = false;
  369. expired->hostname_ = std::string("");
  370. expired->fqdn_fwd_ = false;
  371. expired->fqdn_rev_ = false;
  372. /// @todo: log here that the lease was reused (there's ticket #2524 for
  373. /// logging in libdhcpsrv)
  374. if (!fake_allocation) {
  375. // for REQUEST we do update the lease
  376. LeaseMgrFactory::instance().updateLease6(expired);
  377. }
  378. // We do nothing for SOLICIT. We'll just update database when
  379. // the client gets back to us with REQUEST message.
  380. // it's not really expired at this stage anymore - let's return it as
  381. // an updated lease
  382. return (expired);
  383. }
  384. Lease4Ptr AllocEngine::reuseExpiredLease(Lease4Ptr& expired,
  385. const SubnetPtr& subnet,
  386. const ClientIdPtr& clientid,
  387. const HWAddrPtr& hwaddr,
  388. bool fake_allocation /*= false */ ) {
  389. if (!expired->expired()) {
  390. isc_throw(BadValue, "Attempt to recycle lease that is still valid");
  391. }
  392. // address, lease type and prefixlen (0) stay the same
  393. expired->client_id_ = clientid;
  394. expired->hwaddr_ = hwaddr->hwaddr_;
  395. expired->valid_lft_ = subnet->getValid();
  396. expired->t1_ = subnet->getT1();
  397. expired->t2_ = subnet->getT2();
  398. expired->cltt_ = time(NULL);
  399. expired->subnet_id_ = subnet->getID();
  400. expired->fixed_ = false;
  401. expired->hostname_ = std::string("");
  402. expired->fqdn_fwd_ = false;
  403. expired->fqdn_rev_ = false;
  404. /// @todo: log here that the lease was reused (there's ticket #2524 for
  405. /// logging in libdhcpsrv)
  406. if (!fake_allocation) {
  407. // for REQUEST we do update the lease
  408. LeaseMgrFactory::instance().updateLease4(expired);
  409. }
  410. // We do nothing for SOLICIT. We'll just update database when
  411. // the client gets back to us with REQUEST message.
  412. // it's not really expired at this stage anymore - let's return it as
  413. // an updated lease
  414. return (expired);
  415. }
  416. Lease6Ptr AllocEngine::createLease6(const Subnet6Ptr& subnet,
  417. const DuidPtr& duid,
  418. uint32_t iaid,
  419. const IOAddress& addr,
  420. bool fake_allocation /*= false */ ) {
  421. Lease6Ptr lease(new Lease6(Lease6::LEASE_IA_NA, addr, duid, iaid,
  422. subnet->getPreferred(), subnet->getValid(),
  423. subnet->getT1(), subnet->getT2(), subnet->getID()));
  424. if (!fake_allocation) {
  425. // That is a real (REQUEST) allocation
  426. bool status = LeaseMgrFactory::instance().addLease(lease);
  427. if (status) {
  428. return (lease);
  429. } else {
  430. // One of many failures with LeaseMgr (e.g. lost connection to the
  431. // database, database failed etc.). One notable case for that
  432. // is that we are working in multi-process mode and we lost a race
  433. // (some other process got that address first)
  434. return (Lease6Ptr());
  435. }
  436. } else {
  437. // That is only fake (SOLICIT without rapid-commit) allocation
  438. // It is for advertise only. We should not insert the lease into LeaseMgr,
  439. // but rather check that we could have inserted it.
  440. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(addr);
  441. if (!existing) {
  442. return (lease);
  443. } else {
  444. return (Lease6Ptr());
  445. }
  446. }
  447. }
  448. Lease4Ptr AllocEngine::createLease4(const SubnetPtr& subnet,
  449. const DuidPtr& clientid,
  450. const HWAddrPtr& hwaddr,
  451. const IOAddress& addr,
  452. bool fake_allocation /*= false */ ) {
  453. if (!hwaddr) {
  454. isc_throw(BadValue, "Can't create a lease with NULL HW address");
  455. }
  456. time_t now = time(NULL);
  457. // @todo: remove this kludge after ticket #2590 is implemented
  458. std::vector<uint8_t> local_copy;
  459. if (clientid) {
  460. local_copy = clientid->getDuid();
  461. }
  462. Lease4Ptr lease(new Lease4(addr, &hwaddr->hwaddr_[0], hwaddr->hwaddr_.size(),
  463. &local_copy[0], local_copy.size(), subnet->getValid(),
  464. subnet->getT1(), subnet->getT2(), now,
  465. subnet->getID()));
  466. if (!fake_allocation) {
  467. // That is a real (REQUEST) allocation
  468. bool status = LeaseMgrFactory::instance().addLease(lease);
  469. if (status) {
  470. return (lease);
  471. } else {
  472. // One of many failures with LeaseMgr (e.g. lost connection to the
  473. // database, database failed etc.). One notable case for that
  474. // is that we are working in multi-process mode and we lost a race
  475. // (some other process got that address first)
  476. return (Lease4Ptr());
  477. }
  478. } else {
  479. // That is only fake (DISCOVER) allocation
  480. // It is for OFFER only. We should not insert the lease into LeaseMgr,
  481. // but rather check that we could have inserted it.
  482. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(addr);
  483. if (!existing) {
  484. return (lease);
  485. } else {
  486. return (Lease4Ptr());
  487. }
  488. }
  489. }
  490. AllocEngine::~AllocEngine() {
  491. // no need to delete allocator. smart_ptr will do the trick for us
  492. }
  493. }; // end of isc::dhcp namespace
  494. }; // end of isc namespace