alloc_engine.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 <string.h>
  18. using namespace isc::asiolink;
  19. namespace isc {
  20. namespace dhcp {
  21. AllocEngine::IterativeAllocator::IterativeAllocator()
  22. :Allocator() {
  23. }
  24. isc::asiolink::IOAddress
  25. AllocEngine::IterativeAllocator::increaseAddress(const isc::asiolink::IOAddress& addr) {
  26. // Get a buffer holding an address.
  27. const std::vector<uint8_t>& vec = addr.toBytes();
  28. // Get the address length.
  29. const int len = vec.size();
  30. // Since the same array will be used to hold the IPv4 and IPv6
  31. // address we have to make sure that the size of the array
  32. // we allocate will work for both types of address.
  33. BOOST_STATIC_ASSERT(V4ADDRESS_LEN <= V6ADDRESS_LEN);
  34. uint8_t packed[V6ADDRESS_LEN];
  35. // Copy the address. It can be either V4 or V6.
  36. std::memcpy(packed, &vec[0], len);
  37. // Start increasing the least significant byte
  38. for (int i = len - 1; i >= 0; --i) {
  39. ++packed[i];
  40. // if we haven't overflowed (0xff -> 0x0), than we are done
  41. if (packed[i] != 0) {
  42. break;
  43. }
  44. }
  45. return (IOAddress::fromBytes(addr.getFamily(), packed));
  46. }
  47. isc::asiolink::IOAddress
  48. AllocEngine::IterativeAllocator::pickAddress(const Subnet6Ptr& subnet,
  49. const DuidPtr&,
  50. const IOAddress&) {
  51. // Let's get the last allocated address. It is usually set correctly,
  52. // but there are times when it won't be (like after removing a pool or
  53. // perhaps restaring the server).
  54. IOAddress last = subnet->getLastAllocated();
  55. const Pool6Collection& pools = subnet->getPools();
  56. if (pools.empty()) {
  57. isc_throw(AllocFailed, "No pools defined in selected subnet");
  58. }
  59. // first we need to find a pool the last address belongs to.
  60. Pool6Collection::const_iterator it;
  61. for (it = pools.begin(); it != pools.end(); ++it) {
  62. if ((*it)->inRange(last)) {
  63. break;
  64. }
  65. }
  66. // last one was bogus for one of several reasons:
  67. // - we just booted up and that's the first address we're allocating
  68. // - a subnet was removed or other reconfiguration just completed
  69. // - perhaps allocation algorithm was changed
  70. if (it == pools.end()) {
  71. // ok to access first element directly. We checked that pools is non-empty
  72. IOAddress next = pools[0]->getFirstAddress();
  73. subnet->setLastAllocated(next);
  74. return (next);
  75. }
  76. // Ok, we have a pool that the last address belonged to, let's use it.
  77. IOAddress next = increaseAddress(last); // basically addr++
  78. if ((*it)->inRange(next)) {
  79. // the next one is in the pool as well, so we haven't hit pool boundary yet
  80. subnet->setLastAllocated(next);
  81. return (next);
  82. }
  83. // We hit pool boundary, let's try to jump to the next pool and try again
  84. ++it;
  85. if (it == pools.end()) {
  86. // Really out of luck today. That was the last pool. Let's rewind
  87. // to the beginning.
  88. next = pools[0]->getFirstAddress();
  89. subnet->setLastAllocated(next);
  90. return (next);
  91. }
  92. // there is a next pool, let's try first adddress from it
  93. next = (*it)->getFirstAddress();
  94. subnet->setLastAllocated(next);
  95. return (next);
  96. }
  97. AllocEngine::HashedAllocator::HashedAllocator()
  98. :Allocator() {
  99. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  100. }
  101. isc::asiolink::IOAddress
  102. AllocEngine::HashedAllocator::pickAddress(const Subnet6Ptr&,
  103. const DuidPtr&,
  104. const IOAddress&) {
  105. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  106. }
  107. AllocEngine::RandomAllocator::RandomAllocator()
  108. :Allocator() {
  109. isc_throw(NotImplemented, "Random allocator is not implemented");
  110. }
  111. isc::asiolink::IOAddress
  112. AllocEngine::RandomAllocator::pickAddress(const Subnet6Ptr&,
  113. const DuidPtr&,
  114. const IOAddress&) {
  115. isc_throw(NotImplemented, "Random allocator is not implemented");
  116. }
  117. AllocEngine::AllocEngine(AllocType engine_type, unsigned int attempts)
  118. :attempts_(attempts) {
  119. switch (engine_type) {
  120. case ALLOC_ITERATIVE:
  121. allocator_ = boost::shared_ptr<Allocator>(new IterativeAllocator());
  122. break;
  123. case ALLOC_HASHED:
  124. allocator_ = boost::shared_ptr<Allocator>(new HashedAllocator());
  125. break;
  126. case ALLOC_RANDOM:
  127. allocator_ = boost::shared_ptr<Allocator>(new RandomAllocator());
  128. break;
  129. default:
  130. isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
  131. }
  132. }
  133. Lease6Ptr
  134. AllocEngine::allocateAddress6(const Subnet6Ptr& subnet,
  135. const DuidPtr& duid,
  136. uint32_t iaid,
  137. const IOAddress& hint,
  138. bool fake_allocation /* = false */ ) {
  139. // That check is not necessary. We create allocator in AllocEngine
  140. // constructor
  141. if (!allocator_) {
  142. isc_throw(InvalidOperation, "No allocator selected");
  143. }
  144. // check if there's existing lease for that subnet/duid/iaid combination.
  145. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(*duid, iaid, subnet->getID());
  146. if (existing) {
  147. // we have a lease already. This is a returning client, probably after
  148. // his reboot.
  149. return (existing);
  150. }
  151. // check if the hint is in pool and is available
  152. if (subnet->inPool(hint)) {
  153. existing = LeaseMgrFactory::instance().getLease6(hint);
  154. if (!existing) {
  155. /// @todo: check if the hint is reserved once we have host support
  156. /// implemented
  157. // the hint is valid and not currently used, let's create a lease for it
  158. Lease6Ptr lease = createLease(subnet, duid, iaid, hint, fake_allocation);
  159. // It can happen that the lease allocation failed (we could have lost
  160. // the race condition. That means that the hint is lo longer usable and
  161. // we need to continue the regular allocation path.
  162. if (lease) {
  163. return (lease);
  164. }
  165. } else {
  166. if (existing->expired()) {
  167. return (reuseExpiredLease(existing, subnet, duid, iaid,
  168. fake_allocation));
  169. }
  170. }
  171. }
  172. // Hint is in the pool but is not available. Search the pool until first of
  173. // the following occurs:
  174. // - we find a free address
  175. // - we find an address for which the lease has expired
  176. // - we exhaust number of tries
  177. //
  178. // @todo: Current code does not handle pool exhaustion well. It will be
  179. // improved. Current problems:
  180. // 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
  181. // 10 addresses), we will iterate over it 100 times before giving up
  182. // 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
  183. // 3. the whole concept of infinite attempts is just asking for infinite loop
  184. // We may consider some form or reference counting (this pool has X addresses
  185. // left), but this has one major problem. We exactly control allocation
  186. // moment, but we currently do not control expiration time at all
  187. unsigned int i = attempts_;
  188. do {
  189. IOAddress candidate = allocator_->pickAddress(subnet, duid, hint);
  190. /// @todo: check if the address is reserved once we have host support
  191. /// implemented
  192. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(candidate);
  193. if (!existing) {
  194. // there's no existing lease for selected candidate, so it is
  195. // free. Let's allocate it.
  196. Lease6Ptr lease = createLease(subnet, duid, iaid, candidate,
  197. fake_allocation);
  198. if (lease) {
  199. return (lease);
  200. }
  201. // Although the address was free just microseconds ago, it may have
  202. // been taken just now. If the lease insertion fails, we continue
  203. // allocation attempts.
  204. } else {
  205. if (existing->expired()) {
  206. return (reuseExpiredLease(existing, subnet, duid, iaid,
  207. fake_allocation));
  208. }
  209. }
  210. // continue trying allocation until we run out of attempts
  211. // (or attempts are set to 0, which means infinite)
  212. --i;
  213. } while ( i || !attempts_);
  214. isc_throw(AllocFailed, "Failed to allocate address after " << attempts_
  215. << " tries");
  216. }
  217. Lease6Ptr AllocEngine::reuseExpiredLease(Lease6Ptr& expired,
  218. const Subnet6Ptr& subnet,
  219. const DuidPtr& duid,
  220. uint32_t iaid,
  221. bool fake_allocation /*= false */ ) {
  222. if (!expired->expired()) {
  223. isc_throw(BadValue, "Attempt to recycle lease that is still valid");
  224. }
  225. // address, lease type and prefixlen (0) stay the same
  226. expired->iaid_ = iaid;
  227. expired->duid_ = duid;
  228. expired->preferred_lft_ = subnet->getPreferred();
  229. expired->valid_lft_ = subnet->getValid();
  230. expired->t1_ = subnet->getT1();
  231. expired->t2_ = subnet->getT2();
  232. expired->cltt_ = time(NULL);
  233. expired->subnet_id_ = subnet->getID();
  234. expired->fixed_ = false;
  235. expired->hostname_ = std::string("");
  236. expired->fqdn_fwd_ = false;
  237. expired->fqdn_rev_ = false;
  238. /// @todo: log here that the lease was reused (there's ticket #2524 for
  239. /// logging in libdhcpsrv)
  240. if (!fake_allocation) {
  241. // for REQUEST we do update the lease
  242. LeaseMgrFactory::instance().updateLease6(expired);
  243. }
  244. // We do nothing for SOLICIT. We'll just update database when
  245. // the client gets back to us with REQUEST message.
  246. // it's not really expired at this stage anymore - let's return it as
  247. // an updated lease
  248. return (expired);
  249. }
  250. Lease6Ptr AllocEngine::createLease(const Subnet6Ptr& subnet,
  251. const DuidPtr& duid,
  252. uint32_t iaid,
  253. const IOAddress& addr,
  254. bool fake_allocation /*= false */ ) {
  255. Lease6Ptr lease(new Lease6(Lease6::LEASE_IA_NA, addr, duid, iaid,
  256. subnet->getPreferred(), subnet->getValid(),
  257. subnet->getT1(), subnet->getT2(), subnet->getID()));
  258. if (!fake_allocation) {
  259. // That is a real (REQUEST) allocation
  260. bool status = LeaseMgrFactory::instance().addLease(lease);
  261. if (status) {
  262. return (lease);
  263. } else {
  264. // One of many failures with LeaseMgr (e.g. lost connection to the
  265. // database, database failed etc.). One notable case for that
  266. // is that we are working in multi-process mode and we lost a race
  267. // (some other process got that address first)
  268. return (Lease6Ptr());
  269. }
  270. } else {
  271. // That is only fake (SOLICIT without rapid-commit) allocation
  272. // It is for advertise only. We should not insert the lease into LeaseMgr,
  273. // but rather check that we could have inserted it.
  274. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(addr);
  275. if (!existing) {
  276. return (lease);
  277. } else {
  278. return (Lease6Ptr());
  279. }
  280. }
  281. }
  282. AllocEngine::~AllocEngine() {
  283. // no need to delete allocator. smart_ptr will do the trick for us
  284. }
  285. }; // end of isc::dhcp namespace
  286. }; // end of isc namespace