alloc_engine.cc 21 KB

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