Kea 2.5.5
alloc_engine.cc
Go to the documentation of this file.
1// Copyright (C) 2012-2023 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
7#include <config.h>
8
9#include <dhcp/dhcp6.h>
10#include <dhcp/pkt4.h>
11#include <dhcp/pkt6.h>
12#include <dhcp/option_int.h>
13#include <dhcp_ddns/ncr_msg.h>
16#include <dhcpsrv/cfgmgr.h>
17#include <dhcpsrv/dhcpsrv_log.h>
18#include <dhcpsrv/host_mgr.h>
19#include <dhcpsrv/host.h>
23#include <dhcpsrv/network.h>
27#include <hooks/hooks_manager.h>
29#include <stats/stats_mgr.h>
30#include <util/encode/hex.h>
31#include <util/stopwatch.h>
32#include <hooks/server_hooks.h>
33
34#include <boost/foreach.hpp>
35#include <boost/make_shared.hpp>
36
37#include <algorithm>
38#include <sstream>
39#include <stdint.h>
40#include <string.h>
41#include <utility>
42#include <vector>
43
44using namespace isc::asiolink;
45using namespace isc::dhcp;
46using namespace isc::dhcp_ddns;
47using namespace isc::hooks;
48using namespace isc::stats;
49using namespace isc::util;
50using namespace isc::data;
51namespace ph = std::placeholders;
52
53namespace {
54
56struct AllocEngineHooks {
57 int hook_index_lease4_select_;
58 int hook_index_lease4_renew_;
59 int hook_index_lease4_expire_;
60 int hook_index_lease4_recover_;
61 int hook_index_lease6_select_;
62 int hook_index_lease6_renew_;
63 int hook_index_lease6_rebind_;
64 int hook_index_lease6_expire_;
65 int hook_index_lease6_recover_;
66
68 AllocEngineHooks() {
69 hook_index_lease4_select_ = HooksManager::registerHook("lease4_select");
70 hook_index_lease4_renew_ = HooksManager::registerHook("lease4_renew");
71 hook_index_lease4_expire_ = HooksManager::registerHook("lease4_expire");
72 hook_index_lease4_recover_= HooksManager::registerHook("lease4_recover");
73 hook_index_lease6_select_ = HooksManager::registerHook("lease6_select");
74 hook_index_lease6_renew_ = HooksManager::registerHook("lease6_renew");
75 hook_index_lease6_rebind_ = HooksManager::registerHook("lease6_rebind");
76 hook_index_lease6_expire_ = HooksManager::registerHook("lease6_expire");
77 hook_index_lease6_recover_= HooksManager::registerHook("lease6_recover");
78 }
79};
80
81// Declare a Hooks object. As this is outside any function or method, it
82// will be instantiated (and the constructor run) when the module is loaded.
83// As a result, the hook indexes will be defined before any method in this
84// module is called.
85AllocEngineHooks Hooks;
86
87} // namespace
88
89namespace isc {
90namespace dhcp {
91
93 : attempts_(attempts), incomplete_v4_reclamations_(0),
94 incomplete_v6_reclamations_(0) {
95
96 // Register hook points
97 hook_index_lease4_select_ = Hooks.hook_index_lease4_select_;
98 hook_index_lease6_select_ = Hooks.hook_index_lease6_select_;
99}
100
101} // end of namespace isc::dhcp
102} // end of namespace isc
103
104namespace {
105
115getIPv6Resrv(const SubnetID& subnet_id, const IOAddress& address) {
116 ConstHostCollection reserved;
117 // The global parameter ip-reservations-unique controls whether it is allowed
118 // to specify multiple reservations for the same IP address or delegated prefix
119 // or IP reservations must be unique. Some host backends do not support the
120 // former, thus we can't always use getAll6 calls to get the reservations
121 // for the given IP. When we're in the default mode, when IP reservations
122 // are unique, we should call get6 (supported by all backends). If we're in
123 // the mode in which non-unique reservations are allowed the backends which
124 // don't support it are not used and we can safely call getAll6.
125 if (CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getIPReservationsUnique()) {
126 auto host = HostMgr::instance().get6(subnet_id, address);
127 if (host) {
128 reserved.push_back(host);
129 }
130 } else {
131 auto hosts = HostMgr::instance().getAll6(subnet_id, address);
132 reserved.insert(reserved.end(), hosts.begin(), hosts.end());
133 }
134 return (reserved);
135}
136
149bool
150inAllowedPool(AllocEngine::ClientContext6& ctx, const Lease::Type& lease_type,
151 const IOAddress& address, bool check_subnet) {
152 // If the subnet belongs to a shared network we will be iterating
153 // over the subnets that belong to this shared network.
154 Subnet6Ptr current_subnet = ctx.subnet_;
155 auto const& classes = ctx.query_->getClasses();
156
157 while (current_subnet) {
158 if (current_subnet->clientSupported(classes)) {
159 if (check_subnet) {
160 if (current_subnet->inPool(lease_type, address)) {
161 return (true);
162 }
163 } else {
164 if (current_subnet->inPool(lease_type, address, classes)) {
165 return (true);
166 }
167 }
168 }
169
170 current_subnet = current_subnet->getNextSubnet(ctx.subnet_);
171 }
172
173 return (false);
174}
175
176}
177
178// ##########################################################################
179// # DHCPv6 lease allocation code starts here.
180// ##########################################################################
181
182namespace isc {
183namespace dhcp {
184
186 : query_(), fake_allocation_(false),
187 early_global_reservations_lookup_(false), subnet_(), host_subnet_(),
188 duid_(), hwaddr_(), host_identifiers_(), hosts_(),
189 fwd_dns_update_(false), rev_dns_update_(false), hostname_(),
190 callout_handle_(), ias_(), ddns_params_() {
191}
192
194 const DuidPtr& duid,
195 const bool fwd_dns,
196 const bool rev_dns,
197 const std::string& hostname,
198 const bool fake_allocation,
199 const Pkt6Ptr& query,
200 const CalloutHandlePtr& callout_handle)
201 : query_(query), fake_allocation_(fake_allocation),
202 early_global_reservations_lookup_(false), subnet_(subnet),
203 duid_(duid), hwaddr_(), host_identifiers_(), hosts_(),
204 fwd_dns_update_(fwd_dns), rev_dns_update_(rev_dns), hostname_(hostname),
205 callout_handle_(callout_handle), allocated_resources_(), new_leases_(),
206 ias_(), ddns_params_() {
207
208 // Initialize host identifiers.
209 if (duid) {
210 addHostIdentifier(Host::IDENT_DUID, duid->getDuid());
211 }
212}
213
215 : iaid_(0), type_(Lease::TYPE_NA), hints_(), old_leases_(),
216 changed_leases_(), new_resources_(), ia_rsp_() {
217}
218
219void
222 const uint8_t prefix_len,
223 const uint32_t preferred,
224 const uint32_t valid) {
225 hints_.push_back(Resource(prefix, prefix_len, preferred, valid));
226}
227
228void
231 if (!iaaddr) {
232 isc_throw(BadValue, "IAADDR option pointer is null.");
233 }
234 addHint(iaaddr->getAddress(), 128,
235 iaaddr->getPreferred(), iaaddr->getValid());
236}
237
238void
240IAContext::addHint(const Option6IAPrefixPtr& iaprefix) {
241 if (!iaprefix) {
242 isc_throw(BadValue, "IAPREFIX option pointer is null.");
243 }
244 addHint(iaprefix->getAddress(), iaprefix->getLength(),
245 iaprefix->getPreferred(), iaprefix->getValid());
246}
247
248void
251 const uint8_t prefix_len) {
252 static_cast<void>(new_resources_.insert(Resource(prefix, prefix_len)));
253}
254
255bool
258 const uint8_t prefix_len) const {
259 return (static_cast<bool>(new_resources_.count(Resource(prefix,
260 prefix_len))));
261}
262
263void
266 const uint8_t prefix_len) {
267 static_cast<void>(allocated_resources_.insert(Resource(prefix,
268 prefix_len)));
269}
270
271bool
273isAllocated(const asiolink::IOAddress& prefix, const uint8_t prefix_len) const {
274 return (static_cast<bool>
275 (allocated_resources_.count(Resource(prefix, prefix_len))));
276}
277
281 if (subnet && subnet->getReservationsInSubnet()) {
282 auto host = hosts_.find(subnet->getID());
283 if (host != hosts_.cend()) {
284 return (host->second);
285 }
286 }
287
288 return (globalHost());
289}
290
294 if (subnet && subnet_->getReservationsGlobal()) {
295 auto host = hosts_.find(SUBNET_ID_GLOBAL);
296 if (host != hosts_.cend()) {
297 return (host->second);
298 }
299 }
300
301 return (ConstHostPtr());
302}
303
304bool
306 ConstHostPtr ghost = globalHost();
307 return (ghost && ghost->hasReservation(resv));
308}
309
312 // We already have it return it unless the context subnet has changed.
313 if (ddns_params_ && subnet_ && (subnet_->getID() == ddns_params_->getSubnetId())) {
314 return (ddns_params_);
315 }
316
317 // Doesn't exist yet or is stale, (re)create it.
318 if (subnet_) {
319 ddns_params_ = CfgMgr::instance().getCurrentCfg()->getDdnsParams(subnet_);
320 return (ddns_params_);
321 }
322
323 // Asked for it without a subnet? This case really shouldn't occur but
324 // for now let's return an instance with default values.
325 return (DdnsParamsPtr(new DdnsParams()));
326}
327
328void
330 // If there is no subnet, there is nothing to do.
331 if (!ctx.subnet_) {
332 return;
333 }
334
335 auto subnet = ctx.subnet_;
336
337 // If already done just return.
339 !subnet->getReservationsInSubnet()) {
340 return;
341 }
342
343 // @todo: This code can be trivially optimized.
345 subnet->getReservationsGlobal()) {
347 if (ghost) {
348 ctx.hosts_[SUBNET_ID_GLOBAL] = ghost;
349
350 // If we had only to fetch global reservations it is done.
351 if (!subnet->getReservationsInSubnet()) {
352 return;
353 }
354 }
355 }
356
357 std::map<SubnetID, ConstHostPtr> host_map;
358 SharedNetwork6Ptr network;
359 subnet->getSharedNetwork(network);
360
361 // If the subnet belongs to a shared network it is usually going to be
362 // more efficient to make a query for all reservations for a particular
363 // client rather than a query for each subnet within this shared network.
364 // The only case when it is going to be less efficient is when there are
365 // more host identifier types in use than subnets within a shared network.
366 // As it breaks RADIUS use of host caching this can be disabled by the
367 // host manager.
368 const bool use_single_query = network &&
370 (network->getAllSubnets()->size() > ctx.host_identifiers_.size());
371
372 if (use_single_query) {
373 for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
374 ConstHostCollection hosts = HostMgr::instance().getAll(id_pair.first,
375 &id_pair.second[0],
376 id_pair.second.size());
377 // Store the hosts in the temporary map, because some hosts may
378 // belong to subnets outside of the shared network. We'll need
379 // to eliminate them.
380 for (auto host = hosts.begin(); host != hosts.end(); ++host) {
381 if ((*host)->getIPv6SubnetID() != SUBNET_ID_GLOBAL) {
382 host_map[(*host)->getIPv6SubnetID()] = *host;
383 }
384 }
385 }
386 }
387
388 auto const& classes = ctx.query_->getClasses();
389
390 // We can only search for the reservation if a subnet has been selected.
391 while (subnet) {
392
393 // Only makes sense to get reservations if the client has access
394 // to the class and host reservations are enabled for this subnet.
395 if (subnet->clientSupported(classes) && subnet->getReservationsInSubnet()) {
396 // Iterate over configured identifiers in the order of preference
397 // and try to use each of them to search for the reservations.
398 if (use_single_query) {
399 if (host_map.count(subnet->getID()) > 0) {
400 ctx.hosts_[subnet->getID()] = host_map[subnet->getID()];
401 }
402 } else {
403 for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
404 // Attempt to find a host using a specified identifier.
405 ConstHostPtr host = HostMgr::instance().get6(subnet->getID(),
406 id_pair.first,
407 &id_pair.second[0],
408 id_pair.second.size());
409 // If we found matching host for this subnet.
410 if (host) {
411 ctx.hosts_[subnet->getID()] = host;
412 break;
413 }
414 }
415 }
416 }
417
418 // We need to get to the next subnet if this is a shared network. If it
419 // is not (a plain subnet), getNextSubnet will return NULL and we're
420 // done here.
421 subnet = subnet->getNextSubnet(ctx.subnet_, classes);
422 }
423
424 // The hosts can be used by the server to return reserved options to
425 // the DHCP client. Such options must be encapsulated (i.e., they must
426 // include suboptions).
427 for (auto host : ctx.hosts_) {
428 host.second->encapsulateOptions();
429 }
430}
431
434 ConstHostPtr host;
435 for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
436 // Attempt to find a host using a specified identifier.
437 host = HostMgr::instance().get6(SUBNET_ID_GLOBAL, id_pair.first,
438 &id_pair.second[0], id_pair.second.size());
439
440 // If we found matching global host we're done.
441 if (host) {
442 break;
443 }
444 }
445
446 return (host);
447}
448
451
452 try {
453 if (!ctx.subnet_) {
454 isc_throw(InvalidOperation, "Subnet is required for IPv6 lease allocation");
455 } else
456 if (!ctx.duid_) {
457 isc_throw(InvalidOperation, "DUID is mandatory for IPv6 lease allocation");
458 }
459
460 // Check if there are existing leases for that shared network and
461 // DUID/IAID.
462 Subnet6Ptr subnet = ctx.subnet_;
463 Lease6Collection all_leases =
465 *ctx.duid_,
466 ctx.currentIA().iaid_);
467
468 // Iterate over the leases and eliminate those that are outside of
469 // our shared network.
470 Lease6Collection leases;
471 while (subnet) {
472 for (auto l : all_leases) {
473 if ((l)->subnet_id_ == subnet->getID()) {
474 leases.push_back(l);
475 }
476 }
477
478 subnet = subnet->getNextSubnet(ctx.subnet_);
479 }
480
481 // Now do the checks:
482 // Case 1. if there are no leases, and there are reservations...
483 // 1.1. are the reserved addresses are used by someone else?
484 // yes: we have a problem
485 // no: assign them => done
486 // Case 2. if there are leases and there are no reservations...
487 // 2.1 are the leases reserved for someone else?
488 // yes: release them, assign something else
489 // no: renew them => done
490 // Case 3. if there are leases and there are reservations...
491 // 3.1 are the leases matching reservations?
492 // yes: renew them => done
493 // no: release existing leases, assign new ones based on reservations
494 // Case 4/catch-all. if there are no leases and no reservations...
495 // assign new leases
496
497 // Case 1: There are no leases and there's a reservation for this host.
498 if (leases.empty() && !ctx.hosts_.empty()) {
499
502 .arg(ctx.query_->getLabel());
503
504 // Try to allocate leases that match reservations. Typically this will
505 // succeed, except cases where the reserved addresses are used by
506 // someone else.
507 allocateReservedLeases6(ctx, leases);
508
509 leases = updateLeaseData(ctx, leases);
510
511 // If not, we'll need to continue and will eventually fall into case 4:
512 // getting a regular lease. That could happen when we're processing
513 // request from client X, there's a reserved address A for X, but
514 // A is currently used by client Y. We can't immediately reassign A
515 // from X to Y, because Y keeps using it, so X would send Decline right
516 // away. Need to wait till Y renews, then we can release A, so it
517 // will become available for X.
518
519 // Case 2: There are existing leases and there are no reservations.
520 //
521 // There is at least one lease for this client and there are no reservations.
522 // We will return these leases for the client, but we may need to update
523 // FQDN information.
524 } else if (!leases.empty() && ctx.hosts_.empty()) {
525
528 .arg(ctx.query_->getLabel());
529
530 // Check if the existing leases are reserved for someone else.
531 // If they're not, we're ok to keep using them.
532 removeNonmatchingReservedLeases6(ctx, leases);
533
534 leases = updateLeaseData(ctx, leases);
535
536 // If leases are empty at this stage, it means that we used to have
537 // leases for this client, but we checked and those leases are reserved
538 // for someone else, so we lost them. We will need to continue and
539 // will finally end up in case 4 (no leases, no reservations), so we'll
540 // assign something new.
541
542 // Case 3: There are leases and there are reservations.
543 } else if (!leases.empty() && !ctx.hosts_.empty()) {
544
547 .arg(ctx.query_->getLabel());
548
549 // First, check if have leases matching reservations, and add new
550 // leases if we don't have them.
551 allocateReservedLeases6(ctx, leases);
552
553 // leases now contain both existing and new leases that were created
554 // from reservations.
555
556 // Second, let's remove leases that are reserved for someone else.
557 // This applies to any existing leases. This will not happen frequently,
558 // but it may happen with the following chain of events:
559 // 1. client A gets address X;
560 // 2. reservation for client B for address X is made by a administrator;
561 // 3. client A reboots
562 // 4. client A requests the address (X) he got previously
563 removeNonmatchingReservedLeases6(ctx, leases);
564
565 // leases now contain existing and new leases, but we removed those
566 // leases that are reserved for someone else (non-matching reserved).
567
568 // There's one more check to do. Let's remove leases that are not
569 // matching reservations, i.e. if client X has address A, but there's
570 // a reservation for address B, we should release A and reassign B.
571 // Caveat: do this only if we have at least one reserved address.
572 removeNonreservedLeases6(ctx, leases);
573
574 // All checks are done. Let's hope we have some leases left.
575
576 // Update any leases we have left.
577 leases = updateLeaseData(ctx, leases);
578
579 // If we don't have any leases at this stage, it means that we hit
580 // one of the following cases:
581 // - we have a reservation, but it's not for this IAID/ia-type and
582 // we had to return the address we were using
583 // - we have a reservation for this iaid/ia-type, but the reserved
584 // address is currently used by someone else. We can't assign it
585 // yet.
586 // - we had an address, but we just discovered that it's reserved for
587 // someone else, so we released it.
588 }
589
590 if (leases.empty()) {
591 // Case 4/catch-all: One of the following is true:
592 // - we don't have leases and there are no reservations
593 // - we used to have leases, but we lost them, because they are now
594 // reserved for someone else
595 // - we have a reservation, but it is not usable yet, because the address
596 // is still used by someone else
597 //
598 // In any case, we need to go through normal lease assignment process
599 // for now. This is also a catch-all or last resort approach, when we
600 // couldn't find any reservations (or couldn't use them).
601
604 .arg(ctx.query_->getLabel());
605
606 leases = allocateUnreservedLeases6(ctx);
607 }
608
609 if (!leases.empty()) {
610 // If there are any leases allocated, let's store in them in the
611 // IA context so as they are available when we process subsequent
612 // IAs.
613 BOOST_FOREACH(Lease6Ptr lease, leases) {
614 ctx.addAllocatedResource(lease->addr_, lease->prefixlen_);
615 ctx.new_leases_.push_back(lease);
616 }
617 return (leases);
618 }
619
620 } catch (const isc::Exception& e) {
621
622 // Some other error, return an empty lease.
624 .arg(ctx.query_->getLabel())
625 .arg(e.what());
626 }
627
628 return (Lease6Collection());
629}
630
632AllocEngine::allocateUnreservedLeases6(ClientContext6& ctx) {
633
634 Lease6Collection leases;
635
637 uint8_t hint_prefix_length = 128;
638 if (!ctx.currentIA().hints_.empty()) {
640 hint = ctx.currentIA().hints_[0].getAddress();
641 hint_prefix_length = ctx.currentIA().hints_[0].getPrefixLength();
642 }
643
644 Subnet6Ptr original_subnet = ctx.subnet_;
645
646 Subnet6Ptr subnet = original_subnet;
647
648 SharedNetwork6Ptr network;
649
650 uint64_t total_attempts = 0;
651
652 // The following counter tracks the number of subnets with matching client
653 // classes from which the allocation engine attempted to assign leases.
654 uint64_t subnets_with_unavail_leases = 0;
655 // The following counter tracks the number of subnets in which there were
656 // no matching pools for the client.
657 uint64_t subnets_with_unavail_pools = 0;
658
659 CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
660
661 // In the case of PDs, the allocation engine will try to match pools with
662 // the delegated prefix length matching the one provided in the hint. If the
663 // hint does not provide a preferred delegated prefix length (value is 0),
664 // the allocation engine will match any pool (any greater delegated prefix
665 // length pool). The match type for the pools is ignored for non PDs.
666 Lease6Ptr hint_lease;
667 bool search_hint_lease = true;
669 if (ctx.currentIA().type_ == Lease::TYPE_PD) {
670 // If the hint has a value of 128, the code might be broken as the hint
671 // was added with the default value 128 for prefix_len by the addHint
672 // function instead of 0. However 128 is not a valid value anyway so it
673 // is reset to 0 (use any delegated prefix length available).
674 if (hint_prefix_length == 128) {
675 hint_prefix_length = 0;
676 }
677 if (!hint_prefix_length) {
678 prefix_length_match = Allocator::PREFIX_LEN_HIGHER;
679 }
680 }
681
682 // Try the first allocation using PREFIX_LEN_EQUAL (or in case of PDs,
683 // PREFIX_LEN_HIGHER when there is no valid delegated prefix length in the
684 // provided hint)
685 Lease6Ptr lease = allocateBestMatch(ctx, hint_lease, search_hint_lease,
686 hint, hint_prefix_length, subnet,
687 network, total_attempts,
688 subnets_with_unavail_leases,
689 subnets_with_unavail_pools,
690 callout_status, prefix_length_match);
691
692 // Try the second allocation using PREFIX_LEN_LOWER only for PDs if the
693 // first allocation using PREFIX_LEN_EQUAL failed (there was a specific
694 // delegated prefix length hint requested).
695 if (!lease && ctx.currentIA().type_ == Lease::TYPE_PD &&
696 prefix_length_match == Allocator::PREFIX_LEN_EQUAL) {
697 prefix_length_match = Allocator::PREFIX_LEN_LOWER;
698 lease = allocateBestMatch(ctx, hint_lease, search_hint_lease, hint,
699 hint_prefix_length, subnet, network,
700 total_attempts, subnets_with_unavail_leases,
701 subnets_with_unavail_pools, callout_status,
702 prefix_length_match);
703 }
704
705 // Try the third allocation using PREFIX_LEN_HIGHER only for PDs if the
706 // second allocation using PREFIX_LEN_LOWER failed (there was a specific
707 // delegated prefix length hint requested).
708 if (!lease && ctx.currentIA().type_ == Lease::TYPE_PD &&
709 prefix_length_match == Allocator::PREFIX_LEN_LOWER) {
710 prefix_length_match = Allocator::PREFIX_LEN_HIGHER;
711 lease = allocateBestMatch(ctx, hint_lease, search_hint_lease, hint,
712 hint_prefix_length, subnet, network,
713 total_attempts, subnets_with_unavail_leases,
714 subnets_with_unavail_pools, callout_status,
715 prefix_length_match);
716 }
717
718 if (lease) {
719 leases.push_back(lease);
720 return (leases);
721 }
722
723 auto const& classes = ctx.query_->getClasses();
724
725 if (network) {
726 // The client is in the shared network. Let's log the high level message
727 // indicating which shared network the client belongs to.
729 .arg(ctx.query_->getLabel())
730 .arg(network->getName())
731 .arg(subnets_with_unavail_leases)
732 .arg(subnets_with_unavail_pools);
733 StatsMgr::instance().addValue("v6-allocation-fail-shared-network",
734 static_cast<int64_t>(1));
735 StatsMgr::instance().addValue(
736 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
737 "v6-allocation-fail-shared-network"),
738 static_cast<int64_t>(1));
739 } else {
740 // The client is not connected to a shared network. It is connected
741 // to a subnet. Let's log the ID of that subnet.
742 std::string shared_network = ctx.subnet_->getSharedNetworkName();
743 if (shared_network.empty()) {
744 shared_network = "(none)";
745 }
747 .arg(ctx.query_->getLabel())
748 .arg(ctx.subnet_->toText())
749 .arg(ctx.subnet_->getID())
750 .arg(shared_network);
751 StatsMgr::instance().addValue("v6-allocation-fail-subnet",
752 static_cast<int64_t>(1));
753 StatsMgr::instance().addValue(
754 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
755 "v6-allocation-fail-subnet"),
756 static_cast<int64_t>(1));
757 }
758 if (total_attempts == 0) {
759 // In this case, it seems that none of the pools in the subnets could
760 // be used for that client, both in case the client is connected to
761 // a shared network or to a single subnet. Apparently, the client was
762 // rejected to use the pools because of the client classes' mismatch.
764 .arg(ctx.query_->getLabel());
765 StatsMgr::instance().addValue("v6-allocation-fail-no-pools",
766 static_cast<int64_t>(1));
767 StatsMgr::instance().addValue(
768 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
769 "v6-allocation-fail-no-pools"),
770 static_cast<int64_t>(1));
771 } else {
772 // This is an old log message which provides a number of attempts
773 // made by the allocation engine to allocate a lease. The only case
774 // when we don't want to log this message is when the number of
775 // attempts is zero (condition above), because it would look silly.
777 .arg(ctx.query_->getLabel())
778 .arg(total_attempts);
779 StatsMgr::instance().addValue("v6-allocation-fail",
780 static_cast<int64_t>(1));
781 StatsMgr::instance().addValue(
782 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
783 "v6-allocation-fail"),
784 static_cast<int64_t>(1));
785 }
786
787 if (!classes.empty()) {
789 .arg(ctx.query_->getLabel())
790 .arg(classes.toText());
791 StatsMgr::instance().addValue("v6-allocation-fail-classes",
792 static_cast<int64_t>(1));
793 StatsMgr::instance().addValue(
794 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
795 "v6-allocation-fail-classes"),
796 static_cast<int64_t>(1));
797 }
798
799 // We failed to allocate anything. Let's return empty collection.
800 return (Lease6Collection());
801}
802
804AllocEngine::allocateBestMatch(ClientContext6& ctx,
805 Lease6Ptr& hint_lease,
806 bool& search_hint_lease,
807 const isc::asiolink::IOAddress& hint,
808 uint8_t hint_prefix_length,
809 Subnet6Ptr original_subnet,
810 SharedNetwork6Ptr& network,
811 uint64_t& total_attempts,
812 uint64_t& subnets_with_unavail_leases,
813 uint64_t& subnets_with_unavail_pools,
815 Allocator::PrefixLenMatchType prefix_length_match) {
816 auto const& classes = ctx.query_->getClasses();
817 Pool6Ptr pool;
818 Subnet6Ptr subnet = original_subnet;
819
820 Lease6Ptr usable_hint_lease;
821 if (!search_hint_lease) {
822 usable_hint_lease = hint_lease;
823 }
824 for (; subnet; subnet = subnet->getNextSubnet(original_subnet)) {
825 if (!subnet->clientSupported(classes)) {
826 continue;
827 }
828
829 ctx.subnet_ = subnet;
830
831 // check if the hint is in pool and is available
832 // This is equivalent of subnet->inPool(hint), but returns the pool
833 pool = boost::dynamic_pointer_cast<Pool6>
834 (subnet->getPool(ctx.currentIA().type_, classes, hint));
835
836 // check if the pool is allowed
837 if (!pool || !pool->clientSupported(classes)) {
838 continue;
839 }
840
841 if (ctx.currentIA().type_ == Lease::TYPE_PD &&
842 !Allocator::isValidPrefixPool(prefix_length_match, pool,
843 hint_prefix_length)) {
844 continue;
845 }
846
847 bool in_subnet = subnet->getReservationsInSubnet();
848
850 if (search_hint_lease) {
851 search_hint_lease = false;
852 hint_lease = LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_, hint);
853 usable_hint_lease = hint_lease;
854 }
855 if (!usable_hint_lease) {
856
857 // In-pool reservations: Check if this address is reserved for someone
858 // else. There is no need to check for whom it is reserved, because if
859 // it has been reserved for us we would have already allocated a lease.
860
862 // When out-of-pool flag is true the server may assume that all host
863 // reservations are for addresses that do not belong to the dynamic
864 // pool. Therefore, it can skip the reservation checks when dealing
865 // with in-pool addresses.
866 if (in_subnet &&
867 (!subnet->getReservationsOutOfPool() ||
868 !subnet->inPool(ctx.currentIA().type_, hint))) {
869 hosts = getIPv6Resrv(subnet->getID(), hint);
870 }
871
872 if (hosts.empty()) {
873
874 // If the in-pool reservations are disabled, or there is no
875 // reservation for a given hint, we're good to go.
876
877 // The hint is valid and not currently used, let's create a
878 // lease for it
879 Lease6Ptr new_lease = createLease6(ctx, hint, pool->getLength(), callout_status);
880
881 // It can happen that the lease allocation failed (we could
882 // have lost the race condition. That means that the hint is
883 // no longer usable and we need to continue the regular
884 // allocation path.
885 if (new_lease) {
887 return (new_lease);
888 }
889 } else {
892 .arg(ctx.query_->getLabel())
893 .arg(hint.toText());
894 }
895
896 } else if (usable_hint_lease->expired()) {
897
898 // If the lease is expired, we may likely reuse it, but...
900 // When out-of-pool flag is true the server may assume that all host
901 // reservations are for addresses that do not belong to the dynamic
902 // pool. Therefore, it can skip the reservation checks when dealing
903 // with in-pool addresses.
904 if (in_subnet &&
905 (!subnet->getReservationsOutOfPool() ||
906 !subnet->inPool(ctx.currentIA().type_, hint))) {
907 hosts = getIPv6Resrv(subnet->getID(), hint);
908 }
909
910 // Let's check if there is a reservation for this address.
911 if (hosts.empty()) {
912
913 // Copy an existing, expired lease so as it can be returned
914 // to the caller.
915 Lease6Ptr old_lease(new Lease6(*usable_hint_lease));
916 ctx.currentIA().old_leases_.push_back(old_lease);
917
919 Lease6Ptr lease = reuseExpiredLease(usable_hint_lease, ctx,
920 pool->getLength(),
921 callout_status);
922
924 return (lease);
925
926 } else {
929 .arg(ctx.query_->getLabel())
930 .arg(hint.toText());
931 }
932 }
933 }
934
935 // We have the choice in the order checking the lease and
936 // the reservation. The default is to begin by the lease
937 // if the multi-threading is disabled.
938 bool check_reservation_first = MultiThreadingMgr::instance().getMode();
939 // If multi-threading is disabled, honor the configured order for host
940 // reservations lookup.
941 if (!check_reservation_first) {
942 check_reservation_first = CfgMgr::instance().getCurrentCfg()->getReservationsLookupFirst();
943 }
944
945 // Need to check if the subnet belongs to a shared network. If so,
946 // we might be able to find a better subnet for lease allocation,
947 // for which it is more likely that there are some leases available.
948 // If we stick to the selected subnet, we may end up walking over
949 // the entire subnet (or more subnets) to discover that the pools
950 // have been exhausted. Using a subnet from which a lease was
951 // assigned most recently is an optimization which increases
952 // the likelihood of starting from the subnet which pools are not
953 // exhausted.
954
955 original_subnet->getSharedNetwork(network);
956 if (network) {
957 // This would try to find a subnet with the same set of classes
958 // as the current subnet, but with the more recent "usage timestamp".
959 // This timestamp is only updated for the allocations made with an
960 // allocator (unreserved lease allocations), not the static
961 // allocations or requested addresses.
962 original_subnet = network->getPreferredSubnet(original_subnet, ctx.currentIA().type_);
963 }
964
965 ctx.subnet_ = subnet = original_subnet;
966
967 for (; subnet; subnet = subnet->getNextSubnet(original_subnet)) {
968 if (!subnet->clientSupported(classes)) {
969 continue;
970 }
971
972 // The hint was useless (it was not provided at all, was used by someone else,
973 // was out of pool or reserved for someone else). Search the pool until first
974 // of the following occurs:
975 // - we find a free address
976 // - we find an address for which the lease has expired
977 // - we exhaust number of tries
978 uint128_t const possible_attempts =
979 subnet->getPoolCapacity(ctx.currentIA().type_,
980 classes,
981 prefix_length_match,
982 hint_prefix_length);
983
984 // If the number of tries specified in the allocation engine constructor
985 // is set to 0 (unlimited) or the pools capacity is lower than that number,
986 // let's use the pools capacity as the maximum number of tries. Trying
987 // more than the actual pools capacity is a waste of time. If the specified
988 // number of tries is lower than the pools capacity, use that number.
989 uint128_t const max_attempts =
990 (attempts_ == 0 || possible_attempts < attempts_) ?
991 possible_attempts :
992 attempts_;
993
994 if (max_attempts > 0) {
995 // If max_attempts is greater than 0, there are some pools in this subnet
996 // from which we can potentially get a lease.
997 ++subnets_with_unavail_leases;
998 } else {
999 // If max_attempts is 0, it is an indication that there are no pools
1000 // in the subnet from which we can get a lease.
1001 ++subnets_with_unavail_pools;
1002 continue;
1003 }
1004
1005 bool in_subnet = subnet->getReservationsInSubnet();
1006 bool out_of_pool = subnet->getReservationsOutOfPool();
1007
1008 // Set the default status code in case the lease6_select callouts
1009 // do not exist and the callout handle has a status returned by
1010 // any of the callouts already invoked for this packet.
1011 if (ctx.callout_handle_) {
1012 ctx.callout_handle_->setStatus(CalloutHandle::NEXT_STEP_CONTINUE);
1013 }
1014
1015 for (uint64_t i = 0; i < max_attempts; ++i) {
1016 ++total_attempts;
1017
1018 auto allocator = subnet->getAllocator(ctx.currentIA().type_);
1020
1021 // The first step is to find out prefix length. It is 128 for
1022 // non-PD leases.
1023 uint8_t prefix_len = 128;
1024 if (ctx.currentIA().type_ == Lease::TYPE_PD) {
1025 candidate = allocator->pickPrefix(classes, pool, ctx.duid_,
1026 prefix_length_match, hint,
1027 hint_prefix_length);
1028 if (pool) {
1029 prefix_len = pool->getLength();
1030 }
1031 } else {
1032 candidate = allocator->pickAddress(classes, ctx.duid_, hint);
1033 }
1034
1035 // An allocator may return zero address when it has pools exhausted.
1036 if (candidate.isV6Zero()) {
1037 break;
1038 }
1039
1040 // First check for reservation when it is the choice.
1041 if (check_reservation_first && in_subnet && !out_of_pool) {
1042 auto hosts = getIPv6Resrv(subnet->getID(), candidate);
1043 if (!hosts.empty()) {
1044 // Don't allocate.
1045 continue;
1046 }
1047 }
1048
1049 // Check if the resource is busy i.e. can be being allocated
1050 // by another thread to another client.
1051 ResourceHandler resource_handler;
1052 if (MultiThreadingMgr::instance().getMode() &&
1053 !resource_handler.tryLock(ctx.currentIA().type_, candidate)) {
1054 // Don't allocate.
1055 continue;
1056 }
1057
1058 // Look for an existing lease for the candidate.
1059 Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_,
1060 candidate);
1061
1062 if (!existing) {
1066 if (!check_reservation_first && in_subnet && !out_of_pool) {
1067 auto hosts = getIPv6Resrv(subnet->getID(), candidate);
1068 if (!hosts.empty()) {
1069 // Don't allocate.
1070 continue;
1071 }
1072 }
1073
1074 // there's no existing lease for selected candidate, so it is
1075 // free. Let's allocate it.
1076
1077 ctx.subnet_ = subnet;
1078 Lease6Ptr new_lease = createLease6(ctx, candidate, prefix_len, callout_status);
1079 if (new_lease) {
1080 // We are allocating a new lease (not renewing). So, the
1081 // old lease should be NULL.
1082 ctx.currentIA().old_leases_.clear();
1083
1084 return (new_lease);
1085
1086 } else if (ctx.callout_handle_ &&
1087 (callout_status != CalloutHandle::NEXT_STEP_CONTINUE)) {
1088 // Don't retry when the callout status is not continue.
1089 break;
1090 }
1091
1092 // Although the address was free just microseconds ago, it may have
1093 // been taken just now. If the lease insertion fails, we continue
1094 // allocation attempts.
1095 } else if (existing->expired()) {
1096 // Make sure it's not reserved.
1097 if (!check_reservation_first && in_subnet && !out_of_pool) {
1098 auto hosts = getIPv6Resrv(subnet->getID(), candidate);
1099 if (!hosts.empty()) {
1100 // Don't allocate.
1101 continue;
1102 }
1103 }
1104
1105 // Copy an existing, expired lease so as it can be returned
1106 // to the caller.
1107 Lease6Ptr old_lease(new Lease6(*existing));
1108 ctx.currentIA().old_leases_.push_back(old_lease);
1109
1110 ctx.subnet_ = subnet;
1111 existing = reuseExpiredLease(existing, ctx, prefix_len,
1112 callout_status);
1113
1114 return (existing);
1115 }
1116 }
1117 }
1118 return (Lease6Ptr());
1119}
1120
1121void
1122AllocEngine::allocateReservedLeases6(ClientContext6& ctx,
1123 Lease6Collection& existing_leases) {
1124
1125 // If there are no reservations or the reservation is v4, there's nothing to do.
1126 if (ctx.hosts_.empty()) {
1129 .arg(ctx.query_->getLabel());
1130 return;
1131 }
1132
1133 // Let's convert this from Lease::Type to IPv6Reserv::Type
1134 IPv6Resrv::Type type = ctx.currentIA().type_ == Lease::TYPE_NA ?
1136
1137 // We want to avoid allocating new lease for an IA if there is already
1138 // a valid lease for which client has reservation. So, we first check if
1139 // we already have a lease for a reserved address or prefix.
1140 BOOST_FOREACH(const Lease6Ptr& lease, existing_leases) {
1141 if ((lease->valid_lft_ != 0)) {
1142 if ((ctx.hosts_.count(lease->subnet_id_) > 0) &&
1143 ctx.hosts_[lease->subnet_id_]->hasReservation(makeIPv6Resrv(*lease))) {
1144 // We found existing lease for a reserved address or prefix.
1145 // We'll simply extend the lifetime of the lease.
1148 .arg(ctx.query_->getLabel())
1149 .arg(lease->typeToText(lease->type_))
1150 .arg(lease->addr_.toText());
1151
1152 // Besides IP reservations we're also going to return other reserved
1153 // parameters, such as hostname. We want to hand out the hostname value
1154 // from the same reservation entry as IP addresses. Thus, let's see if
1155 // there is any hostname reservation.
1156 if (!ctx.host_subnet_) {
1157 SharedNetwork6Ptr network;
1158 ctx.subnet_->getSharedNetwork(network);
1159 if (network) {
1160 // Remember the subnet that holds this preferred host
1161 // reservation. The server will use it to return appropriate
1162 // FQDN, classes etc.
1163 ctx.host_subnet_ = network->getSubnet(lease->subnet_id_);
1164 ConstHostPtr host = ctx.hosts_[lease->subnet_id_];
1165 // If there is a hostname reservation here we should stick
1166 // to this reservation. By updating the hostname in the
1167 // context we make sure that the database is updated with
1168 // this new value and the server doesn't need to do it and
1169 // its processing performance is not impacted by the hostname
1170 // updates.
1171 if (host && !host->getHostname().empty()) {
1172 // We have to determine whether the hostname is generated
1173 // in response to client's FQDN or not. If yes, we will
1174 // need to qualify the hostname. Otherwise, we just use
1175 // the hostname as it is specified for the reservation.
1176 OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1177 ctx.hostname_ = CfgMgr::instance().getD2ClientMgr().
1178 qualifyName(host->getHostname(), *ctx.getDdnsParams(),
1179 static_cast<bool>(fqdn));
1180 }
1181 }
1182 }
1183
1184 // Got a lease for a reservation in this IA.
1185 return;
1186 }
1187 }
1188 }
1189
1190 // There is no lease for a reservation in this IA. So, let's now iterate
1191 // over reservations specified and try to allocate one of them for the IA.
1192
1193 auto const& classes = ctx.query_->getClasses();
1194 for (Subnet6Ptr subnet = ctx.subnet_; subnet;
1195 subnet = subnet->getNextSubnet(ctx.subnet_)) {
1196
1197 SubnetID subnet_id = subnet->getID();
1198
1199 // No hosts for this subnet or the subnet not supported.
1200 if (!subnet->clientSupported(classes) || ctx.hosts_.count(subnet_id) == 0) {
1201 continue;
1202 }
1203
1204 ConstHostPtr host = ctx.hosts_[subnet_id];
1205
1206 bool in_subnet = subnet->getReservationsInSubnet();
1207
1208 // Get the IPv6 reservations of specified type.
1209 const IPv6ResrvRange& reservs = host->getIPv6Reservations(type);
1210 BOOST_FOREACH(IPv6ResrvTuple type_lease_tuple, reservs) {
1211 // We do have a reservation for address or prefix.
1212 const IOAddress& addr = type_lease_tuple.second.getPrefix();
1213 uint8_t prefix_len = type_lease_tuple.second.getPrefixLen();
1214
1215 // We have allocated this address/prefix while processing one of the
1216 // previous IAs, so let's try another reservation.
1217 if (ctx.isAllocated(addr, prefix_len)) {
1218 continue;
1219 }
1220
1221 // The out-of-pool flag indicates that no client should be assigned
1222 // reserved addresses from within the dynamic pool, and for that
1223 // reason look only for reservations that are outside the pools,
1224 // hence the inPool check.
1225 if (!in_subnet ||
1226 (subnet->getReservationsOutOfPool() &&
1227 subnet->inPool(ctx.currentIA().type_, addr))) {
1228 continue;
1229 }
1230
1231 // If there's a lease for this address, let's not create it.
1232 // It doesn't matter whether it is for this client or for someone else.
1233 if (!LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_,
1234 addr)) {
1235
1236 // Let's remember the subnet from which the reserved address has been
1237 // allocated. We'll use this subnet for allocating other reserved
1238 // resources.
1239 ctx.subnet_ = subnet;
1240
1241 if (!ctx.host_subnet_) {
1242 ctx.host_subnet_ = subnet;
1243 if (!host->getHostname().empty()) {
1244 // If there is a hostname reservation here we should stick
1245 // to this reservation. By updating the hostname in the
1246 // context we make sure that the database is updated with
1247 // this new value and the server doesn't need to do it and
1248 // its processing performance is not impacted by the hostname
1249 // updates.
1250
1251 // We have to determine whether the hostname is generated
1252 // in response to client's FQDN or not. If yes, we will
1253 // need to qualify the hostname. Otherwise, we just use
1254 // the hostname as it is specified for the reservation.
1255 OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1256 ctx.hostname_ = CfgMgr::instance().getD2ClientMgr().
1257 qualifyName(host->getHostname(), *ctx.getDdnsParams(),
1258 static_cast<bool>(fqdn));
1259 }
1260 }
1261
1262 // Ok, let's create a new lease...
1263 CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
1264 Lease6Ptr lease = createLease6(ctx, addr, prefix_len, callout_status);
1265
1266 // ... and add it to the existing leases list.
1267 existing_leases.push_back(lease);
1268
1269 if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1271 .arg(addr.toText())
1272 .arg(ctx.query_->getLabel());
1273 } else {
1275 .arg(addr.toText())
1276 .arg(static_cast<int>(prefix_len))
1277 .arg(ctx.query_->getLabel());
1278 }
1279
1280 // We found a lease for this client and this IA. Let's return.
1281 // Returning after the first lease was assigned is useful if we
1282 // have multiple reservations for the same client. If the client
1283 // sends 2 IAs, the first time we call allocateReservedLeases6 will
1284 // use the first reservation and return. The second time, we'll
1285 // go over the first reservation, but will discover that there's
1286 // a lease corresponding to it and will skip it and then pick
1287 // the second reservation and turn it into the lease. This approach
1288 // would work for any number of reservations.
1289 return;
1290 }
1291 }
1292 }
1293
1294 // Found no subnet reservations so now try the global reservation.
1295 allocateGlobalReservedLeases6(ctx, existing_leases);
1296}
1297
1298void
1299AllocEngine::allocateGlobalReservedLeases6(ClientContext6& ctx,
1300 Lease6Collection& existing_leases) {
1301 // Get the global host
1302 ConstHostPtr ghost = ctx.globalHost();
1303 if (!ghost) {
1304 return;
1305 }
1306
1307 // We want to avoid allocating a new lease for an IA if there is already
1308 // a valid lease for which client has reservation. So, we first check if
1309 // we already have a lease for a reserved address or prefix.
1310 BOOST_FOREACH(const Lease6Ptr& lease, existing_leases) {
1311 if ((lease->valid_lft_ != 0) &&
1312 (ghost->hasReservation(makeIPv6Resrv(*lease)))) {
1313 // We found existing lease for a reserved address or prefix.
1314 // We'll simply extend the lifetime of the lease.
1317 .arg(ctx.query_->getLabel())
1318 .arg(lease->typeToText(lease->type_))
1319 .arg(lease->addr_.toText());
1320
1321 // Besides IP reservations we're also going to return other reserved
1322 // parameters, such as hostname. We want to hand out the hostname value
1323 // from the same reservation entry as IP addresses. Thus, let's see if
1324 // there is any hostname reservation.
1325 if (!ghost->getHostname().empty()) {
1326 // We have to determine whether the hostname is generated
1327 // in response to client's FQDN or not. If yes, we will
1328 // need to qualify the hostname. Otherwise, we just use
1329 // the hostname as it is specified for the reservation.
1330 OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1331 ctx.hostname_ = CfgMgr::instance().getD2ClientMgr().
1332 qualifyName(ghost->getHostname(), *ctx.getDdnsParams(),
1333 static_cast<bool>(fqdn));
1334 }
1335
1336 // Got a lease for a reservation in this IA.
1337 return;
1338 }
1339 }
1340
1341 // There is no lease for a reservation in this IA. So, let's now iterate
1342 // over reservations specified and try to allocate one of them for the IA.
1343
1344 // Let's convert this from Lease::Type to IPv6Reserv::Type
1345 IPv6Resrv::Type type = ctx.currentIA().type_ == Lease::TYPE_NA ?
1347
1348 const IPv6ResrvRange& reservs = ghost->getIPv6Reservations(type);
1349 BOOST_FOREACH(IPv6ResrvTuple type_lease_tuple, reservs) {
1350 // We do have a reservation for address or prefix.
1351 const IOAddress& addr = type_lease_tuple.second.getPrefix();
1352 uint8_t prefix_len = type_lease_tuple.second.getPrefixLen();
1353
1354 // We have allocated this address/prefix while processing one of the
1355 // previous IAs, so let's try another reservation.
1356 if (ctx.isAllocated(addr, prefix_len)) {
1357 continue;
1358 }
1359
1360 // If there's a lease for this address, let's not create it.
1361 // It doesn't matter whether it is for this client or for someone else.
1362 if (!LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_, addr)) {
1363
1364 // Check the feasibility of this address within this shared-network.
1365 // Assign the context's subnet accordingly.
1366 // Only necessary for IA_NA
1367 if (type == IPv6Resrv::TYPE_NA) {
1368 bool valid_subnet = false;
1369 auto subnet = ctx.subnet_;
1370 while (subnet) {
1371 if (subnet->inRange(addr)) {
1372 valid_subnet = true;
1373 break;
1374 }
1375
1376 subnet = subnet->getNextSubnet(ctx.subnet_);
1377 }
1378
1379 if (!valid_subnet) {
1382 .arg(addr.toText())
1383 .arg(labelNetworkOrSubnet(ctx.subnet_));
1384 continue;
1385 }
1386
1387 ctx.subnet_ = subnet;
1388 }
1389
1390 if (!ghost->getHostname().empty()) {
1391 // If there is a hostname reservation here we should stick
1392 // to this reservation. By updating the hostname in the
1393 // context we make sure that the database is updated with
1394 // this new value and the server doesn't need to do it and
1395 // its processing performance is not impacted by the hostname
1396 // updates.
1397
1398 // We have to determine whether the hostname is generated
1399 // in response to client's FQDN or not. If yes, we will
1400 // need to qualify the hostname. Otherwise, we just use
1401 // the hostname as it is specified for the reservation.
1402 OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1403 ctx.hostname_ = CfgMgr::instance().getD2ClientMgr().
1404 qualifyName(ghost->getHostname(), *ctx.getDdnsParams(),
1405 static_cast<bool>(fqdn));
1406 }
1407
1408 // Ok, let's create a new lease...
1409 CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
1410 Lease6Ptr lease = createLease6(ctx, addr, prefix_len, callout_status);
1411
1412 // ... and add it to the existing leases list.
1413 existing_leases.push_back(lease);
1414
1415 if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1417 .arg(addr.toText())
1418 .arg(ctx.query_->getLabel());
1419 } else {
1421 .arg(addr.toText())
1422 .arg(static_cast<int>(prefix_len))
1423 .arg(ctx.query_->getLabel());
1424 }
1425
1426 // We found a lease for this client and this IA. Let's return.
1427 // Returning after the first lease was assigned is useful if we
1428 // have multiple reservations for the same client. If the client
1429 // sends 2 IAs, the first time we call allocateReservedLeases6 will
1430 // use the first reservation and return. The second time, we'll
1431 // go over the first reservation, but will discover that there's
1432 // a lease corresponding to it and will skip it and then pick
1433 // the second reservation and turn it into the lease. This approach
1434 // would work for any number of reservations.
1435 return;
1436 }
1437 }
1438}
1439
1440void
1441AllocEngine::removeNonmatchingReservedLeases6(ClientContext6& ctx,
1442 Lease6Collection& existing_leases) {
1443 // If there are no leases (so nothing to remove) just return.
1444 if (existing_leases.empty() || !ctx.subnet_) {
1445 return;
1446 }
1447 // If host reservation is disabled (so there are no reserved leases)
1448 // use the simplified version.
1449 if (!ctx.subnet_->getReservationsInSubnet() &&
1450 !ctx.subnet_->getReservationsGlobal()) {
1451 removeNonmatchingReservedNoHostLeases6(ctx, existing_leases);
1452 return;
1453 }
1454
1455 // We need a copy, so we won't be iterating over a container and
1456 // removing from it at the same time. It's only a copy of pointers,
1457 // so the operation shouldn't be that expensive.
1458 Lease6Collection copy = existing_leases;
1459
1460 BOOST_FOREACH(const Lease6Ptr& candidate, copy) {
1461 // If we have reservation we should check if the reservation is for
1462 // the candidate lease. If so, we simply accept the lease.
1463 IPv6Resrv resv = makeIPv6Resrv(*candidate);
1464 if ((ctx.hasGlobalReservation(resv)) ||
1465 ((ctx.hosts_.count(candidate->subnet_id_) > 0) &&
1466 (ctx.hosts_[candidate->subnet_id_]->hasReservation(resv)))) {
1467 // We have a subnet reservation
1468 continue;
1469 }
1470
1471 // The candidate address doesn't appear to be reserved for us.
1472 // We have to make a bit more expensive operation here to retrieve
1473 // the reservation for the candidate lease and see if it is
1474 // reserved for someone else.
1475 auto hosts = getIPv6Resrv(ctx.subnet_->getID(), candidate->addr_);
1476 // If lease is not reserved to someone else, it means that it can
1477 // be allocated to us from a dynamic pool, but we must check if
1478 // this lease belongs to any pool. If it does, we can proceed to
1479 // checking the next lease.
1480 if (hosts.empty() && inAllowedPool(ctx, candidate->type_,
1481 candidate->addr_, false)) {
1482 continue;
1483 }
1484
1485 if (!hosts.empty()) {
1486 // Ok, we have a problem. This host has a lease that is reserved
1487 // for someone else. We need to recover from this.
1488 if (hosts.size() == 1) {
1489 if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1491 .arg(candidate->addr_.toText())
1492 .arg(ctx.duid_->toText())
1493 .arg(hosts.front()->getIdentifierAsText());
1494 } else {
1496 .arg(candidate->addr_.toText())
1497 .arg(static_cast<int>(candidate->prefixlen_))
1498 .arg(ctx.duid_->toText())
1499 .arg(hosts.front()->getIdentifierAsText());
1500 }
1501 } else {
1502 if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1504 .arg(candidate->addr_.toText())
1505 .arg(ctx.duid_->toText())
1506 .arg(hosts.size());
1507 } else {
1509 .arg(candidate->addr_.toText())
1510 .arg(static_cast<int>(candidate->prefixlen_))
1511 .arg(ctx.duid_->toText())
1512 .arg(hosts.size());
1513 }
1514 }
1515 }
1516
1517 // Remove this lease from LeaseMgr as it is reserved to someone
1518 // else or doesn't belong to a pool.
1519 if (!LeaseMgrFactory::instance().deleteLease(candidate)) {
1520 // Concurrent delete performed by other instance which should
1521 // properly handle dns and stats updates.
1522 continue;
1523 }
1524
1525 // Update DNS if needed.
1526 queueNCR(CHG_REMOVE, candidate);
1527
1528 // Need to decrease statistic for assigned addresses.
1529 StatsMgr::instance().addValue(
1530 StatsMgr::generateName("subnet", candidate->subnet_id_,
1531 ctx.currentIA().type_ == Lease::TYPE_NA ?
1532 "assigned-nas" : "assigned-pds"),
1533 static_cast<int64_t>(-1));
1534
1535 const auto& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(candidate->subnet_id_);
1536 if (subnet) {
1537 const auto& pool = subnet->getPool(ctx.currentIA().type_, candidate->addr_, false);
1538 if (pool) {
1539 StatsMgr::instance().addValue(
1540 StatsMgr::generateName("subnet", subnet->getID(),
1541 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ? "pool" : "pd-pool", pool->getID(),
1542 ctx.currentIA().type_ == Lease::TYPE_NA ? "assigned-nas" : "assigned-pds")),
1543 static_cast<int64_t>(-1));
1544 }
1545 }
1546
1547 // In principle, we could trigger a hook here, but we will do this
1548 // only if we get serious complaints from actual users. We want the
1549 // conflict resolution procedure to really work and user libraries
1550 // should not interfere with it.
1551
1552 // Add this to the list of removed leases.
1553 ctx.currentIA().old_leases_.push_back(candidate);
1554
1555 // Let's remove this candidate from existing leases
1556 removeLeases(existing_leases, candidate->addr_);
1557 }
1558}
1559
1560void
1561AllocEngine::removeNonmatchingReservedNoHostLeases6(ClientContext6& ctx,
1562 Lease6Collection& existing_leases) {
1563 // We need a copy, so we won't be iterating over a container and
1564 // removing from it at the same time. It's only a copy of pointers,
1565 // so the operation shouldn't be that expensive.
1566 Lease6Collection copy = existing_leases;
1567
1568 BOOST_FOREACH(const Lease6Ptr& candidate, copy) {
1569 // Lease can be allocated to us from a dynamic pool, but we must
1570 // check if this lease belongs to any allowed pool. If it does,
1571 // we can proceed to checking the next lease.
1572 if (inAllowedPool(ctx, candidate->type_,
1573 candidate->addr_, false)) {
1574 continue;
1575 }
1576
1577 // Remove this lease from LeaseMgr as it doesn't belong to a pool.
1578 if (!LeaseMgrFactory::instance().deleteLease(candidate)) {
1579 // Concurrent delete performed by other instance which should
1580 // properly handle dns and stats updates.
1581 continue;
1582 }
1583
1584 // Update DNS if needed.
1585 queueNCR(CHG_REMOVE, candidate);
1586
1587 // Need to decrease statistic for assigned addresses.
1588 StatsMgr::instance().addValue(
1589 StatsMgr::generateName("subnet", candidate->subnet_id_,
1590 ctx.currentIA().type_ == Lease::TYPE_NA ?
1591 "assigned-nas" : "assigned-pds"),
1592 static_cast<int64_t>(-1));
1593
1594 const auto& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getBySubnetId(candidate->subnet_id_);
1595 if (subnet) {
1596 const auto& pool = subnet->getPool(candidate->type_, candidate->addr_, false);
1597 if (pool) {
1598 StatsMgr::instance().addValue(
1599 StatsMgr::generateName("subnet", subnet->getID(),
1600 StatsMgr::generateName(candidate->type_ == Lease::TYPE_NA ? "pool" : "pd-pool", pool->getID(),
1601 candidate->type_ == Lease::TYPE_NA ? "assigned-nas" : "assigned-pds")),
1602 static_cast<int64_t>(-1));
1603 }
1604 }
1605
1606 // Add this to the list of removed leases.
1607 ctx.currentIA().old_leases_.push_back(candidate);
1608
1609 // Let's remove this candidate from existing leases
1610 removeLeases(existing_leases, candidate->addr_);
1611 }
1612}
1613
1614bool
1615AllocEngine::removeLeases(Lease6Collection& container, const asiolink::IOAddress& addr) {
1616
1617 bool removed = false;
1618 for (Lease6Collection::iterator lease = container.begin();
1619 lease != container.end(); ++lease) {
1620 if ((*lease)->addr_ == addr) {
1621 lease->reset();
1622 removed = true;
1623 }
1624 }
1625
1626 // Remove all elements that have NULL value
1627 container.erase(std::remove(container.begin(), container.end(), Lease6Ptr()),
1628 container.end());
1629
1630 return (removed);
1631}
1632
1633void
1634AllocEngine::removeNonreservedLeases6(ClientContext6& ctx,
1635 Lease6Collection& existing_leases) {
1636 // This method removes leases that are not reserved for this host.
1637 // It will keep at least one lease, though, as a fallback.
1638 int total = existing_leases.size();
1639 if (total <= 1) {
1640 return;
1641 }
1642
1643 // This is officially not scary code anymore. iterates and marks specified
1644 // leases for deletion, by setting appropriate pointers to NULL.
1645 for (Lease6Collection::iterator lease = existing_leases.begin();
1646 lease != existing_leases.end(); ++lease) {
1647
1648 // If there is reservation for this keep it.
1649 IPv6Resrv resv = makeIPv6Resrv(*(*lease));
1650 if (ctx.hasGlobalReservation(resv) ||
1651 ((ctx.hosts_.count((*lease)->subnet_id_) > 0) &&
1652 (ctx.hosts_[(*lease)->subnet_id_]->hasReservation(resv)))) {
1653 continue;
1654 }
1655
1656 // @todo - If this is for a fake_allocation, we should probably
1657 // not be deleting the lease or removing DNS entries. We should
1658 // simply remove it from the list.
1659 // We have reservations, but not for this lease. Release it.
1660 // Remove this lease from LeaseMgr
1661 if (!LeaseMgrFactory::instance().deleteLease(*lease)) {
1662 // Concurrent delete performed by other instance which should
1663 // properly handle dns and stats updates.
1664 continue;
1665 }
1666
1667 // Update DNS if required.
1668 queueNCR(CHG_REMOVE, *lease);
1669
1670 // Need to decrease statistic for assigned addresses.
1671 StatsMgr::instance().addValue(
1672 StatsMgr::generateName("subnet", (*lease)->subnet_id_,
1673 ctx.currentIA().type_ == Lease::TYPE_NA ?
1674 "assigned-nas" : "assigned-pds"),
1675 static_cast<int64_t>(-1));
1676
1677 const auto& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getBySubnetId((*lease)->subnet_id_);
1678 if (subnet) {
1679 const auto& pool = subnet->getPool(ctx.currentIA().type_, (*lease)->addr_, false);
1680 if (pool) {
1681 StatsMgr::instance().addValue(
1682 StatsMgr::generateName("subnet", subnet->getID(),
1683 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ? "pool" : "pd-pool", pool->getID(),
1684 ctx.currentIA().type_ == Lease::TYPE_NA ? "assigned-nas" : "assigned-pds")),
1685 static_cast<int64_t>(-1));
1686 }
1687 }
1688
1690
1691 // Add this to the list of removed leases.
1692 ctx.currentIA().old_leases_.push_back(*lease);
1693
1694 // Set this pointer to NULL. The pointer is still valid. We're just
1695 // setting the Lease6Ptr to NULL value. We'll remove all NULL
1696 // pointers once the loop is finished.
1697 lease->reset();
1698
1699 if (--total == 1) {
1700 // If there's only one lease left, break the loop.
1701 break;
1702 }
1703 }
1704
1705 // Remove all elements that we previously marked for deletion (those that
1706 // have NULL value).
1707 existing_leases.erase(std::remove(existing_leases.begin(),
1708 existing_leases.end(), Lease6Ptr()), existing_leases.end());
1709}
1710
1712AllocEngine::reuseExpiredLease(Lease6Ptr& expired, ClientContext6& ctx,
1713 uint8_t prefix_len,
1714 CalloutHandle::CalloutNextStep& callout_status) {
1715
1716 if (!expired->expired()) {
1717 isc_throw(BadValue, "Attempt to recycle lease that is still valid");
1718 }
1719
1720 if (expired->type_ != Lease::TYPE_PD) {
1721 prefix_len = 128; // non-PD lease types must be always /128
1722 }
1723
1724 if (!ctx.fake_allocation_) {
1725 // The expired lease needs to be reclaimed before it can be reused.
1726 // This includes declined leases for which probation period has
1727 // elapsed.
1728 reclaimExpiredLease(expired, ctx.callout_handle_);
1729 }
1730
1731 // address, lease type and prefixlen (0) stay the same
1732 expired->iaid_ = ctx.currentIA().iaid_;
1733 expired->duid_ = ctx.duid_;
1734
1735 // Calculate life times.
1736 getLifetimes6(ctx, expired->preferred_lft_, expired->valid_lft_);
1737 expired->reuseable_valid_lft_ = 0;
1738
1739 expired->cltt_ = time(NULL);
1740 expired->subnet_id_ = ctx.subnet_->getID();
1741 expired->hostname_ = ctx.hostname_;
1742 expired->fqdn_fwd_ = ctx.fwd_dns_update_;
1743 expired->fqdn_rev_ = ctx.rev_dns_update_;
1744 expired->prefixlen_ = prefix_len;
1745 expired->state_ = Lease::STATE_DEFAULT;
1746
1749 .arg(ctx.query_->getLabel())
1750 .arg(expired->toText());
1751
1752 // Let's execute all callouts registered for lease6_select
1753 if (ctx.callout_handle_ &&
1754 HooksManager::calloutsPresent(hook_index_lease6_select_)) {
1755
1756 // Use the RAII wrapper to make sure that the callout handle state is
1757 // reset when this object goes out of scope. All hook points must do
1758 // it to prevent possible circular dependency between the callout
1759 // handle and its arguments.
1760 ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
1761
1762 // Enable copying options from the packet within hook library.
1763 ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
1764
1765 // Pass necessary arguments
1766
1767 // Pass the original packet
1768 ctx.callout_handle_->setArgument("query6", ctx.query_);
1769
1770 // Subnet from which we do the allocation
1771 ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
1772
1773 // Is this solicit (fake = true) or request (fake = false)
1774 ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
1775
1776 // The lease that will be assigned to a client
1777 ctx.callout_handle_->setArgument("lease6", expired);
1778
1779 // Call the callouts
1780 HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
1781
1782 callout_status = ctx.callout_handle_->getStatus();
1783
1784 // Callouts decided to skip the action. This means that the lease is not
1785 // assigned, so the client will get NoAddrAvail as a result. The lease
1786 // won't be inserted into the database.
1787 if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
1789 return (Lease6Ptr());
1790 }
1791
1796
1797 // Let's use whatever callout returned. Hopefully it is the same lease
1798 // we handed to it.
1799 ctx.callout_handle_->getArgument("lease6", expired);
1800 }
1801
1802 if (!ctx.fake_allocation_) {
1803 // Add (update) the extended information on the lease.
1804 updateLease6ExtendedInfo(expired, ctx);
1805
1806 const auto& pool = ctx.subnet_->getPool(ctx.currentIA().type_, expired->addr_, false);
1807 if (pool) {
1808 expired->pool_id_ = pool->getID();
1809 }
1810
1811 // for REQUEST we do update the lease
1813
1814 // If the lease is in the current subnet we need to account
1815 // for the re-assignment of The lease.
1816 if (ctx.subnet_->inPool(ctx.currentIA().type_, expired->addr_)) {
1817 StatsMgr::instance().addValue(
1818 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1819 ctx.currentIA().type_ == Lease::TYPE_NA ?
1820 "assigned-nas" : "assigned-pds"),
1821 static_cast<int64_t>(1));
1822
1823 StatsMgr::instance().addValue(
1824 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1825 ctx.currentIA().type_ == Lease::TYPE_NA ?
1826 "cumulative-assigned-nas" : "cumulative-assigned-pds"),
1827 static_cast<int64_t>(1));
1828
1829 if (pool) {
1830 StatsMgr::instance().addValue(
1831 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1832 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ?
1833 "pool" : "pd-pool", pool->getID(),
1834 ctx.currentIA().type_ == Lease::TYPE_NA ?
1835 "assigned-nas" : "assigned-pds")),
1836 static_cast<int64_t>(1));
1837
1838 StatsMgr::instance().addValue(
1839 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1840 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ?
1841 "pool" : "pd-pool", pool->getID(),
1842 ctx.currentIA().type_ == Lease::TYPE_NA ?
1843 "cumulative-assigned-nas" : "cumulative-assigned-pds")),
1844 static_cast<int64_t>(1));
1845 }
1846
1847 StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
1848 "cumulative-assigned-nas" : "cumulative-assigned-pds",
1849 static_cast<int64_t>(1));
1850 }
1851 }
1852
1853 // We do nothing for SOLICIT. We'll just update database when
1854 // the client gets back to us with REQUEST message.
1855
1856 // it's not really expired at this stage anymore - let's return it as
1857 // an updated lease
1858 return (expired);
1859}
1860
1861void
1862AllocEngine::getLifetimes6(ClientContext6& ctx, uint32_t& preferred, uint32_t& valid) {
1863 // If the triplets are specified in one of our classes use it.
1864 // We use the first one we find for each lifetime.
1865 Triplet<uint32_t> candidate_preferred;
1866 Triplet<uint32_t> candidate_valid;
1867 const ClientClasses classes = ctx.query_->getClasses();
1868 if (!classes.empty()) {
1869 // Let's get class definitions
1870 const ClientClassDictionaryPtr& dict =
1871 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
1872
1873 // Iterate over the assigned class definitions.
1874 int have_both = 0;
1875 for (auto name = classes.cbegin();
1876 name != classes.cend() && have_both < 2; ++name) {
1877 ClientClassDefPtr cl = dict->findClass(*name);
1878 if (candidate_preferred.unspecified() &&
1879 (cl && (!cl->getPreferred().unspecified()))) {
1880 candidate_preferred = cl->getPreferred();
1881 ++have_both;
1882 }
1883
1884 if (candidate_valid.unspecified() &&
1885 (cl && (!cl->getValid().unspecified()))) {
1886 candidate_valid = cl->getValid();
1887 ++have_both;
1888 }
1889 }
1890 }
1891
1892 // If no classes specified preferred lifetime, get it from the subnet.
1893 if (!candidate_preferred) {
1894 candidate_preferred = ctx.subnet_->getPreferred();
1895 }
1896
1897 // If no classes specified valid lifetime, get it from the subnet.
1898 if (!candidate_valid) {
1899 candidate_valid = ctx.subnet_->getValid();
1900 }
1901
1902 // Set the outbound parameters to the values we have so far.
1903 preferred = candidate_preferred;
1904 valid = candidate_valid;
1905
1906 // If client requested either value, use the requested value(s) bounded by
1907 // the candidate triplet(s).
1908 if (!ctx.currentIA().hints_.empty()) {
1909 if (ctx.currentIA().hints_[0].getPreferred()) {
1910 preferred = candidate_preferred.get(ctx.currentIA().hints_[0].getPreferred());
1911 }
1912
1913 if (ctx.currentIA().hints_[0].getValid()) {
1914 valid = candidate_valid.get(ctx.currentIA().hints_[0].getValid());
1915 }
1916 }
1917
1918 // If preferred isn't set or insane, calculate it as valid_lft * 0.625.
1919 if (!preferred || preferred > valid) {
1920 preferred = ((valid * 5)/8);
1923 .arg(ctx.query_->getLabel())
1924 .arg(preferred);
1925 }
1926}
1927
1928Lease6Ptr AllocEngine::createLease6(ClientContext6& ctx,
1929 const IOAddress& addr,
1930 uint8_t prefix_len,
1931 CalloutHandle::CalloutNextStep& callout_status) {
1932
1933 if (ctx.currentIA().type_ != Lease::TYPE_PD) {
1934 prefix_len = 128; // non-PD lease types must be always /128
1935 }
1936
1937 uint32_t preferred = 0;
1938 uint32_t valid = 0;
1939 getLifetimes6(ctx, preferred, valid);
1940
1941 Lease6Ptr lease(new Lease6(ctx.currentIA().type_, addr, ctx.duid_,
1942 ctx.currentIA().iaid_, preferred,
1943 valid, ctx.subnet_->getID(),
1944 ctx.hwaddr_, prefix_len));
1945
1946 lease->fqdn_fwd_ = ctx.fwd_dns_update_;
1947 lease->fqdn_rev_ = ctx.rev_dns_update_;
1948 lease->hostname_ = ctx.hostname_;
1949
1950 // Let's execute all callouts registered for lease6_select
1951 if (ctx.callout_handle_ &&
1952 HooksManager::calloutsPresent(hook_index_lease6_select_)) {
1953
1954 // Use the RAII wrapper to make sure that the callout handle state is
1955 // reset when this object goes out of scope. All hook points must do
1956 // it to prevent possible circular dependency between the callout
1957 // handle and its arguments.
1958 ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
1959
1960 // Enable copying options from the packet within hook library.
1961 ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
1962
1963 // Pass necessary arguments
1964
1965 // Pass the original packet
1966 ctx.callout_handle_->setArgument("query6", ctx.query_);
1967
1968 // Subnet from which we do the allocation
1969 ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
1970
1971 // Is this solicit (fake = true) or request (fake = false)
1972 ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
1973
1974 // The lease that will be assigned to a client
1975 ctx.callout_handle_->setArgument("lease6", lease);
1976
1977 // This is the first callout, so no need to clear any arguments
1978 HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
1979
1980 callout_status = ctx.callout_handle_->getStatus();
1981
1982 // Callouts decided to skip the action. This means that the lease is not
1983 // assigned, so the client will get NoAddrAvail as a result. The lease
1984 // won't be inserted into the database.
1985 if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
1987 return (Lease6Ptr());
1988 }
1989
1990 // Let's use whatever callout returned. Hopefully it is the same lease
1991 // we handed to it.
1992 ctx.callout_handle_->getArgument("lease6", lease);
1993 }
1994
1995 if (!ctx.fake_allocation_) {
1996 // Add (update) the extended information on the lease.
1997 updateLease6ExtendedInfo(lease, ctx);
1998
1999 const auto& pool = ctx.subnet_->getPool(ctx.currentIA().type_, lease->addr_, false);
2000 if (pool) {
2001 lease->pool_id_ = pool->getID();
2002 }
2003
2004 // That is a real (REQUEST) allocation
2005 bool status = LeaseMgrFactory::instance().addLease(lease);
2006
2007 if (status) {
2008 // The lease insertion succeeded - if the lease is in the
2009 // current subnet lets bump up the statistic.
2010 if (ctx.subnet_->inPool(ctx.currentIA().type_, addr)) {
2011 StatsMgr::instance().addValue(
2012 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2013 ctx.currentIA().type_ == Lease::TYPE_NA ?
2014 "assigned-nas" : "assigned-pds"),
2015 static_cast<int64_t>(1));
2016
2017 StatsMgr::instance().addValue(
2018 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2019 ctx.currentIA().type_ == Lease::TYPE_NA ?
2020 "cumulative-assigned-nas" : "cumulative-assigned-pds"),
2021 static_cast<int64_t>(1));
2022
2023 if (pool) {
2024 StatsMgr::instance().addValue(
2025 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2026 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ?
2027 "pool" : "pd-pool", pool->getID(),
2028 ctx.currentIA().type_ == Lease::TYPE_NA ?
2029 "assigned-nas" : "assigned-pds")),
2030 static_cast<int64_t>(1));
2031
2032 StatsMgr::instance().addValue(
2033 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2034 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ?
2035 "pool" : "pd-pool", pool->getID(),
2036 ctx.currentIA().type_ == Lease::TYPE_NA ?
2037 "cumulative-assigned-nas" : "cumulative-assigned-pds")),
2038 static_cast<int64_t>(1));
2039 }
2040
2041 StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
2042 "cumulative-assigned-nas" : "cumulative-assigned-pds",
2043 static_cast<int64_t>(1));
2044 }
2045
2046 // Record it so it won't be updated twice.
2047 ctx.currentIA().addNewResource(addr, prefix_len);
2048
2049 return (lease);
2050 } else {
2051 // One of many failures with LeaseMgr (e.g. lost connection to the
2052 // database, database failed etc.). One notable case for that
2053 // is that we are working in multi-process mode and we lost a race
2054 // (some other process got that address first)
2055 return (Lease6Ptr());
2056 }
2057 } else {
2058 // That is only fake (SOLICIT without rapid-commit) allocation
2059
2060 // It is for advertise only. We should not insert the lease and callers
2061 // have already verified the lease does not exist in the database.
2062 return (lease);
2063 }
2064}
2065
2068 try {
2069 if (!ctx.subnet_) {
2070 isc_throw(InvalidOperation, "Subnet is required for allocation");
2071 }
2072
2073 if (!ctx.duid_) {
2074 isc_throw(InvalidOperation, "DUID is mandatory for allocation");
2075 }
2076
2077 // Check if there are any leases for this client.
2078 Subnet6Ptr subnet = ctx.subnet_;
2079 Lease6Collection leases;
2080 while (subnet) {
2081 Lease6Collection leases_subnet =
2083 *ctx.duid_,
2084 ctx.currentIA().iaid_,
2085 subnet->getID());
2086 leases.insert(leases.end(), leases_subnet.begin(), leases_subnet.end());
2087
2088 subnet = subnet->getNextSubnet(ctx.subnet_);
2089 }
2090
2091 if (!leases.empty()) {
2094 .arg(ctx.query_->getLabel());
2095
2096 // Check if the existing leases are reserved for someone else.
2097 // If they're not, we're ok to keep using them.
2098 removeNonmatchingReservedLeases6(ctx, leases);
2099 }
2100
2101 if (!ctx.hosts_.empty()) {
2102
2105 .arg(ctx.query_->getLabel());
2106
2107 // If we have host reservation, allocate those leases.
2108 allocateReservedLeases6(ctx, leases);
2109
2110 // There's one more check to do. Let's remove leases that are not
2111 // matching reservations, i.e. if client X has address A, but there's
2112 // a reservation for address B, we should release A and reassign B.
2113 // Caveat: do this only if we have at least one reserved address.
2114 removeNonreservedLeases6(ctx, leases);
2115 }
2116
2117 // If we happen to removed all leases, get something new for this guy.
2118 // Depending on the configuration, we may enable or disable granting
2119 // new leases during renewals. This is controlled with the
2120 // allow_new_leases_in_renewals_ field.
2121 if (leases.empty()) {
2122
2125 .arg(ctx.query_->getLabel());
2126
2127 leases = allocateUnreservedLeases6(ctx);
2128 }
2129
2130 // Extend all existing leases that passed all checks.
2131 for (Lease6Collection::iterator l = leases.begin(); l != leases.end(); ++l) {
2132 if (ctx.currentIA().isNewResource((*l)->addr_,
2133 (*l)->prefixlen_)) {
2134 // This lease was just created so is already extended.
2135 continue;
2136 }
2139 .arg(ctx.query_->getLabel())
2140 .arg((*l)->typeToText((*l)->type_))
2141 .arg((*l)->addr_);
2142 extendLease6(ctx, *l);
2143 }
2144
2145 if (!leases.empty()) {
2146 // If there are any leases allocated, let's store in them in the
2147 // IA context so as they are available when we process subsequent
2148 // IAs.
2149 BOOST_FOREACH(Lease6Ptr lease, leases) {
2150 ctx.addAllocatedResource(lease->addr_, lease->prefixlen_);
2151 ctx.new_leases_.push_back(lease);
2152 }
2153 }
2154
2155 return (leases);
2156
2157 } catch (const isc::Exception& e) {
2158
2159 // Some other error, return an empty lease.
2161 .arg(ctx.query_->getLabel())
2162 .arg(e.what());
2163 }
2164
2165 return (Lease6Collection());
2166}
2167
2168void
2169AllocEngine::extendLease6(ClientContext6& ctx, Lease6Ptr lease) {
2170
2171 if (!lease || !ctx.subnet_) {
2172 return;
2173 }
2174
2175 // It is likely that the lease for which we're extending the lifetime doesn't
2176 // belong to the current but a sibling subnet.
2177 if (ctx.subnet_->getID() != lease->subnet_id_) {
2178 SharedNetwork6Ptr network;
2179 ctx.subnet_->getSharedNetwork(network);
2180 if (network) {
2181 Subnet6Ptr subnet = network->getSubnet(SubnetID(lease->subnet_id_));
2182 // Found the actual subnet this lease belongs to. Stick to this
2183 // subnet.
2184 if (subnet) {
2185 ctx.subnet_ = subnet;
2186 }
2187 }
2188 }
2189
2190 // If the lease is not global and it is either out of range (NAs only) or it
2191 // is not permitted by subnet client classification, delete it.
2192 if (!(ctx.hasGlobalReservation(makeIPv6Resrv(*lease))) &&
2193 (((lease->type_ != Lease::TYPE_PD) && !ctx.subnet_->inRange(lease->addr_)) ||
2194 !ctx.subnet_->clientSupported(ctx.query_->getClasses()))) {
2195 // Oh dear, the lease is no longer valid. We need to get rid of it.
2196
2197 // Remove this lease from LeaseMgr
2198 if (!LeaseMgrFactory::instance().deleteLease(lease)) {
2199 // Concurrent delete performed by other instance which should
2200 // properly handle dns and stats updates.
2201 return;
2202 }
2203
2204 // Updated DNS if required.
2205 queueNCR(CHG_REMOVE, lease);
2206
2207 // Need to decrease statistic for assigned addresses.
2208 StatsMgr::instance().addValue(
2209 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2210 ctx.currentIA().type_ == Lease::TYPE_NA ?
2211 "assigned-nas" : "assigned-pds"),
2212 static_cast<int64_t>(-1));
2213
2214 const auto& pool = ctx.subnet_->getPool(ctx.currentIA().type_, lease->addr_, false);
2215 if (pool) {
2216 StatsMgr::instance().addValue(
2217 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2218 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ?
2219 "pool" : "pd-pool", pool->getID(),
2220 ctx.currentIA().type_ == Lease::TYPE_NA ?
2221 "assigned-nas" : "assigned-pds")),
2222 static_cast<int64_t>(-1));
2223 }
2224
2225 // Add it to the removed leases list.
2226 ctx.currentIA().old_leases_.push_back(lease);
2227
2228 return;
2229 }
2230
2233 .arg(ctx.query_->getLabel())
2234 .arg(lease->toText());
2235
2236 // Keep the old data in case the callout tells us to skip update.
2237 Lease6Ptr old_data(new Lease6(*lease));
2238
2239 bool changed = false;
2240
2241 // Calculate life times.
2242 uint32_t current_preferred_lft = lease->preferred_lft_;
2243 getLifetimes6(ctx, lease->preferred_lft_, lease->valid_lft_);
2244
2245 // If either has changed set the changed flag.
2246 if ((lease->preferred_lft_ != current_preferred_lft) ||
2247 (lease->valid_lft_ != lease->current_valid_lft_)) {
2248 changed = true;
2249 }
2250
2251 lease->cltt_ = time(NULL);
2252 if ((lease->fqdn_fwd_ != ctx.fwd_dns_update_) ||
2253 (lease->fqdn_rev_ != ctx.rev_dns_update_) ||
2254 (lease->hostname_ != ctx.hostname_)) {
2255 changed = true;
2256 lease->hostname_ = ctx.hostname_;
2257 lease->fqdn_fwd_ = ctx.fwd_dns_update_;
2258 lease->fqdn_rev_ = ctx.rev_dns_update_;
2259 }
2260 if ((!ctx.hwaddr_ && lease->hwaddr_) ||
2261 (ctx.hwaddr_ &&
2262 (!lease->hwaddr_ || (*ctx.hwaddr_ != *lease->hwaddr_)))) {
2263 changed = true;
2264 lease->hwaddr_ = ctx.hwaddr_;
2265 }
2266 if (lease->state_ != Lease::STATE_DEFAULT) {
2267 changed = true;
2268 lease->state_ = Lease::STATE_DEFAULT;
2269 }
2272 .arg(ctx.query_->getLabel())
2273 .arg(lease->toText());
2274
2275 bool skip = false;
2276 // Get the callouts specific for the processed message and execute them.
2277 int hook_point = ctx.query_->getType() == DHCPV6_RENEW ?
2278 Hooks.hook_index_lease6_renew_ : Hooks.hook_index_lease6_rebind_;
2279 if (HooksManager::calloutsPresent(hook_point)) {
2280 CalloutHandlePtr callout_handle = ctx.callout_handle_;
2281
2282 // Use the RAII wrapper to make sure that the callout handle state is
2283 // reset when this object goes out of scope. All hook points must do
2284 // it to prevent possible circular dependency between the callout
2285 // handle and its arguments.
2286 ScopedCalloutHandleState callout_handle_state(callout_handle);
2287
2288 // Enable copying options from the packet within hook library.
2289 ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
2290
2291 // Pass the original packet
2292 callout_handle->setArgument("query6", ctx.query_);
2293
2294 // Pass the lease to be updated
2295 callout_handle->setArgument("lease6", lease);
2296
2297 // Pass the IA option to be sent in response
2298 if (lease->type_ == Lease::TYPE_NA) {
2299 callout_handle->setArgument("ia_na", ctx.currentIA().ia_rsp_);
2300 } else {
2301 callout_handle->setArgument("ia_pd", ctx.currentIA().ia_rsp_);
2302 }
2303
2304 // Call all installed callouts
2305 HooksManager::callCallouts(hook_point, *callout_handle);
2306
2307 // Callouts decided to skip the next processing step. The next
2308 // processing step would actually renew the lease, so skip at this
2309 // stage means "keep the old lease as it is".
2310 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2311 skip = true;
2314 .arg(ctx.query_->getName());
2315 }
2316
2318 }
2319
2320 if (!skip) {
2321 bool update_stats = false;
2322
2323 // If the lease we're renewing has expired, we need to reclaim this
2324 // lease before we can renew it.
2325 if (old_data->expired()) {
2326 reclaimExpiredLease(old_data, ctx.callout_handle_);
2327
2328 // If the lease is in the current subnet we need to account
2329 // for the re-assignment of the lease.
2330 if (ctx.subnet_->inPool(ctx.currentIA().type_, old_data->addr_)) {
2331 update_stats = true;
2332 }
2333 changed = true;
2334 }
2335
2336 // @todo should we call storeLease6ExtendedInfo() here ?
2337 updateLease6ExtendedInfo(lease, ctx);
2338 if (lease->extended_info_action_ == Lease6::ACTION_UPDATE) {
2339 changed = true;
2340 }
2341
2342 // Try to reuse the lease.
2343 if (!changed) {
2344 setLeaseReusable(lease, current_preferred_lft, ctx);
2345 }
2346
2347 // Now that the lease has been reclaimed, we can go ahead and update it
2348 // in the lease database.
2349 if (lease->reuseable_valid_lft_ == 0) {
2350 const auto& pool = ctx.subnet_->getPool(ctx.currentIA().type_, lease->addr_, false);
2351 if (pool) {
2352 lease->pool_id_ = pool->getID();
2353 }
2355 }
2356
2357 if (update_stats) {
2358 StatsMgr::instance().addValue(
2359 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2360 ctx.currentIA().type_ == Lease::TYPE_NA ?
2361 "assigned-nas" : "assigned-pds"),
2362 static_cast<int64_t>(1));
2363
2364 StatsMgr::instance().addValue(
2365 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2366 ctx.currentIA().type_ == Lease::TYPE_NA ?
2367 "cumulative-assigned-nas" : "cumulative-assigned-pds"),
2368 static_cast<int64_t>(1));
2369
2370 const auto& pool = ctx.subnet_->getPool(ctx.currentIA().type_, lease->addr_, false);
2371 if (pool) {
2372 StatsMgr::instance().addValue(
2373 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2374 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ?
2375 "pool" : "pd-pool", pool->getID(),
2376 ctx.currentIA().type_ == Lease::TYPE_NA ?
2377 "assigned-nas" : "assigned-pds")),
2378 static_cast<int64_t>(1));
2379
2380 StatsMgr::instance().addValue(
2381 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2382 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ?
2383 "pool" : "pd-pool", pool->getID(),
2384 ctx.currentIA().type_ == Lease::TYPE_NA ?
2385 "cumulative-assigned-nas" : "cumulative-assigned-pds")),
2386 static_cast<int64_t>(1));
2387 }
2388
2389 StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
2390 "cumulative-assigned-nas" : "cumulative-assigned-pds",
2391 static_cast<int64_t>(1));
2392 }
2393
2394 } else {
2395 // Copy back the original date to the lease. For MySQL it doesn't make
2396 // much sense, but for memfile, the Lease6Ptr points to the actual lease
2397 // in memfile, so the actual update is performed when we manipulate
2398 // fields of returned Lease6Ptr, the actual updateLease6() is no-op.
2399 *lease = *old_data;
2400 }
2401
2402 // Add the old lease to the changed lease list. This allows the server
2403 // to make decisions regarding DNS updates.
2404 ctx.currentIA().changed_leases_.push_back(old_data);
2405}
2406
2408AllocEngine::updateLeaseData(ClientContext6& ctx, const Lease6Collection& leases) {
2409 Lease6Collection updated_leases;
2410 for (Lease6Collection::const_iterator lease_it = leases.begin();
2411 lease_it != leases.end(); ++lease_it) {
2412 Lease6Ptr lease(new Lease6(**lease_it));
2413 if (ctx.currentIA().isNewResource(lease->addr_, lease->prefixlen_)) {
2414 // This lease was just created so is already up to date.
2415 updated_leases.push_back(lease);
2416 continue;
2417 }
2418
2419 lease->reuseable_valid_lft_ = 0;
2420 lease->fqdn_fwd_ = ctx.fwd_dns_update_;
2421 lease->fqdn_rev_ = ctx.rev_dns_update_;
2422 lease->hostname_ = ctx.hostname_;
2423 uint32_t current_preferred_lft = lease->preferred_lft_;
2424 if (lease->valid_lft_ == 0) {
2425 // The lease was expired by a release: reset zero lifetimes.
2426 getLifetimes6(ctx, lease->preferred_lft_, lease->valid_lft_);
2427 }
2428 if (!ctx.fake_allocation_) {
2429 bool update_stats = false;
2430
2431 if (lease->state_ == Lease::STATE_EXPIRED_RECLAIMED) {
2432 // Transition lease state to default (aka assigned)
2433 lease->state_ = Lease::STATE_DEFAULT;
2434
2435 // If the lease is in the current subnet we need to account
2436 // for the re-assignment of the lease.
2437 if (inAllowedPool(ctx, ctx.currentIA().type_,
2438 lease->addr_, true)) {
2439 update_stats = true;
2440 }
2441 }
2442
2443 bool fqdn_changed = ((lease->type_ != Lease::TYPE_PD) &&
2444 !(lease->hasIdenticalFqdn(**lease_it)));
2445
2446 lease->cltt_ = time(NULL);
2447 if (!fqdn_changed) {
2448 setLeaseReusable(lease, current_preferred_lft, ctx);
2449 }
2450 if (lease->reuseable_valid_lft_ == 0) {
2451 ctx.currentIA().changed_leases_.push_back(*lease_it);
2453 }
2454
2455 if (update_stats) {
2456 StatsMgr::instance().addValue(
2457 StatsMgr::generateName("subnet", lease->subnet_id_,
2458 ctx.currentIA().type_ == Lease::TYPE_NA ?
2459 "assigned-nas" : "assigned-pds"),
2460 static_cast<int64_t>(1));
2461
2462 StatsMgr::instance().addValue(
2463 StatsMgr::generateName("subnet", lease->subnet_id_,
2464 ctx.currentIA().type_ == Lease::TYPE_NA ?
2465 "cumulative-assigned-nas" : "cumulative-assigned-pds"),
2466 static_cast<int64_t>(1));
2467
2468 const auto& pool = ctx.subnet_->getPool(ctx.currentIA().type_, lease->addr_, false);
2469 if (pool) {
2470 StatsMgr::instance().addValue(
2471 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2472 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ?
2473 "pool" : "pd-pool", pool->getID(),
2474 ctx.currentIA().type_ == Lease::TYPE_NA ?
2475 "assigned-nas" : "assigned-pds")),
2476 static_cast<int64_t>(1));
2477
2478 StatsMgr::instance().addValue(
2479 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2480 StatsMgr::generateName(ctx.currentIA().type_ == Lease::TYPE_NA ?
2481 "pool" : "pd-pool", pool->getID(),
2482 ctx.currentIA().type_ == Lease::TYPE_NA ?
2483 "cumulative-assigned-nas" : "cumulative-assigned-pds")),
2484 static_cast<int64_t>(1));
2485 }
2486
2487 StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
2488 "cumulative-assigned-nas" : "cumulative-assigned-pds",
2489 static_cast<int64_t>(1));
2490 }
2491 }
2492
2493 updated_leases.push_back(lease);
2494 }
2495
2496 return (updated_leases);
2497}
2498
2499void
2501 const uint16_t timeout,
2502 const bool remove_lease,
2503 const uint16_t max_unwarned_cycles) {
2504
2507 .arg(max_leases)
2508 .arg(timeout);
2509
2510 try {
2511 reclaimExpiredLeases6Internal(max_leases, timeout, remove_lease,
2512 max_unwarned_cycles);
2513 } catch (const std::exception& ex) {
2516 .arg(ex.what());
2517 }
2518}
2519
2520void
2522 const uint16_t timeout,
2523 const bool remove_lease,
2524 const uint16_t max_unwarned_cycles) {
2525
2526 // Create stopwatch and automatically start it to measure the time
2527 // taken by the routine.
2528 util::Stopwatch stopwatch;
2529
2530 LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2531
2532 // This value indicates if we have been able to deal with all expired
2533 // leases in this pass.
2534 bool incomplete_reclamation = false;
2535 Lease6Collection leases;
2536 // The value of 0 has a special meaning - reclaim all.
2537 if (max_leases > 0) {
2538 // If the value is non-zero, the caller has limited the number of
2539 // leases to reclaim. We obtain one lease more to see if there will
2540 // be still leases left after this pass.
2541 lease_mgr.getExpiredLeases6(leases, max_leases + 1);
2542 // There are more leases expired leases than we will process in this
2543 // pass, so we should mark it as an incomplete reclamation. We also
2544 // remove this extra lease (which we don't want to process anyway)
2545 // from the collection.
2546 if (leases.size() > max_leases) {
2547 leases.pop_back();
2548 incomplete_reclamation = true;
2549 }
2550
2551 } else {
2552 // If there is no limitation on the number of leases to reclaim,
2553 // we will try to process all. Hence, we don't mark it as incomplete
2554 // reclamation just yet.
2555 lease_mgr.getExpiredLeases6(leases, max_leases);
2556 }
2557
2558 // Do not initialize the callout handle until we know if there are any
2559 // lease6_expire callouts installed.
2560 CalloutHandlePtr callout_handle;
2561 if (!leases.empty() &&
2562 HooksManager::calloutsPresent(Hooks.hook_index_lease6_expire_)) {
2563 callout_handle = HooksManager::createCalloutHandle();
2564 }
2565
2566 size_t leases_processed = 0;
2567 BOOST_FOREACH(Lease6Ptr lease, leases) {
2568
2569 try {
2570 // Reclaim the lease.
2571 if (MultiThreadingMgr::instance().getMode()) {
2572 // The reclamation is exclusive of packet processing.
2573 WriteLockGuard exclusive(rw_mutex_);
2574
2575 reclaimExpiredLease(lease, remove_lease, callout_handle);
2576 ++leases_processed;
2577 } else {
2578 reclaimExpiredLease(lease, remove_lease, callout_handle);
2579 ++leases_processed;
2580 }
2581
2582 } catch (const std::exception& ex) {
2584 .arg(lease->addr_.toText())
2585 .arg(ex.what());
2586 }
2587
2588 // Check if we have hit the timeout for running reclamation routine and
2589 // return if we have. We're checking it here, because we always want to
2590 // allow reclaiming at least one lease.
2591 if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
2592 // Timeout. This will likely mean that we haven't been able to process
2593 // all leases we wanted to process. The reclamation pass will be
2594 // probably marked as incomplete.
2595 if (!incomplete_reclamation) {
2596 if (leases_processed < leases.size()) {
2597 incomplete_reclamation = true;
2598 }
2599 }
2600
2603 .arg(timeout);
2604 break;
2605 }
2606 }
2607
2608 // Stop measuring the time.
2609 stopwatch.stop();
2610
2611 // Mark completion of the lease reclamation routine and present some stats.
2614 .arg(leases_processed)
2615 .arg(stopwatch.logFormatTotalDuration());
2616
2617 // Check if this was an incomplete reclamation and increase the number of
2618 // consecutive incomplete reclamations.
2619 if (incomplete_reclamation) {
2620 ++incomplete_v6_reclamations_;
2621 // If the number of incomplete reclamations is beyond the threshold, we
2622 // need to issue a warning.
2623 if ((max_unwarned_cycles > 0) &&
2624 (incomplete_v6_reclamations_ > max_unwarned_cycles)) {
2626 .arg(max_unwarned_cycles);
2627 // We issued a warning, so let's now reset the counter.
2628 incomplete_v6_reclamations_ = 0;
2629 }
2630
2631 } else {
2632 // This was a complete reclamation, so let's reset the counter.
2633 incomplete_v6_reclamations_ = 0;
2634
2637 }
2638}
2639
2640void
2644 .arg(secs);
2645
2646 uint64_t deleted_leases = 0;
2647 try {
2648 // Try to delete leases from the lease database.
2649 LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2650 deleted_leases = lease_mgr.deleteExpiredReclaimedLeases6(secs);
2651
2652 } catch (const std::exception& ex) {
2654 .arg(ex.what());
2655 }
2656
2659 .arg(deleted_leases);
2660}
2661
2662void
2664 const uint16_t timeout,
2665 const bool remove_lease,
2666 const uint16_t max_unwarned_cycles) {
2667
2670 .arg(max_leases)
2671 .arg(timeout);
2672
2673 try {
2674 reclaimExpiredLeases4Internal(max_leases, timeout, remove_lease,
2675 max_unwarned_cycles);
2676 } catch (const std::exception& ex) {
2679 .arg(ex.what());
2680 }
2681}
2682
2683void
2685 const uint16_t timeout,
2686 const bool remove_lease,
2687 const uint16_t max_unwarned_cycles) {
2688
2689 // Create stopwatch and automatically start it to measure the time
2690 // taken by the routine.
2691 util::Stopwatch stopwatch;
2692
2693 LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2694
2695 // This value indicates if we have been able to deal with all expired
2696 // leases in this pass.
2697 bool incomplete_reclamation = false;
2698 Lease4Collection leases;
2699 // The value of 0 has a special meaning - reclaim all.
2700 if (max_leases > 0) {
2701 // If the value is non-zero, the caller has limited the number of
2702 // leases to reclaim. We obtain one lease more to see if there will
2703 // be still leases left after this pass.
2704 lease_mgr.getExpiredLeases4(leases, max_leases + 1);
2705 // There are more leases expired leases than we will process in this
2706 // pass, so we should mark it as an incomplete reclamation. We also
2707 // remove this extra lease (which we don't want to process anyway)
2708 // from the collection.
2709 if (leases.size() > max_leases) {
2710 leases.pop_back();
2711 incomplete_reclamation = true;
2712 }
2713
2714 } else {
2715 // If there is no limitation on the number of leases to reclaim,
2716 // we will try to process all. Hence, we don't mark it as incomplete
2717 // reclamation just yet.
2718 lease_mgr.getExpiredLeases4(leases, max_leases);
2719 }
2720
2721 // Do not initialize the callout handle until we know if there are any
2722 // lease4_expire callouts installed.
2723 CalloutHandlePtr callout_handle;
2724 if (!leases.empty() &&
2725 HooksManager::calloutsPresent(Hooks.hook_index_lease4_expire_)) {
2726 callout_handle = HooksManager::createCalloutHandle();
2727 }
2728
2729 size_t leases_processed = 0;
2730 BOOST_FOREACH(Lease4Ptr lease, leases) {
2731
2732 try {
2733 // Reclaim the lease.
2734 if (MultiThreadingMgr::instance().getMode()) {
2735 // The reclamation is exclusive of packet processing.
2736 WriteLockGuard exclusive(rw_mutex_);
2737
2738 reclaimExpiredLease(lease, remove_lease, callout_handle);
2739 ++leases_processed;
2740 } else {
2741 reclaimExpiredLease(lease, remove_lease, callout_handle);
2742 ++leases_processed;
2743 }
2744
2745 } catch (const std::exception& ex) {
2747 .arg(lease->addr_.toText())
2748 .arg(ex.what());
2749 }
2750
2751 // Check if we have hit the timeout for running reclamation routine and
2752 // return if we have. We're checking it here, because we always want to
2753 // allow reclaiming at least one lease.
2754 if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
2755 // Timeout. This will likely mean that we haven't been able to process
2756 // all leases we wanted to process. The reclamation pass will be
2757 // probably marked as incomplete.
2758 if (!incomplete_reclamation) {
2759 if (leases_processed < leases.size()) {
2760 incomplete_reclamation = true;
2761 }
2762 }
2763
2766 .arg(timeout);
2767 break;
2768 }
2769 }
2770
2771 // Stop measuring the time.
2772 stopwatch.stop();
2773
2774 // Mark completion of the lease reclamation routine and present some stats.
2777 .arg(leases_processed)
2778 .arg(stopwatch.logFormatTotalDuration());
2779
2780 // Check if this was an incomplete reclamation and increase the number of
2781 // consecutive incomplete reclamations.
2782 if (incomplete_reclamation) {
2783 ++incomplete_v4_reclamations_;
2784 // If the number of incomplete reclamations is beyond the threshold, we
2785 // need to issue a warning.
2786 if ((max_unwarned_cycles > 0) &&
2787 (incomplete_v4_reclamations_ > max_unwarned_cycles)) {
2789 .arg(max_unwarned_cycles);
2790 // We issued a warning, so let's now reset the counter.
2791 incomplete_v4_reclamations_ = 0;
2792 }
2793
2794 } else {
2795 // This was a complete reclamation, so let's reset the counter.
2796 incomplete_v4_reclamations_ = 0;
2797
2800 }
2801}
2802
2803template<typename LeasePtrType>
2804void
2805AllocEngine::reclaimExpiredLease(const LeasePtrType& lease, const bool remove_lease,
2806 const CalloutHandlePtr& callout_handle) {
2807 reclaimExpiredLease(lease, remove_lease ? DB_RECLAIM_REMOVE : DB_RECLAIM_UPDATE,
2808 callout_handle);
2809}
2810
2811template<typename LeasePtrType>
2812void
2813AllocEngine::reclaimExpiredLease(const LeasePtrType& lease,
2814 const CalloutHandlePtr& callout_handle) {
2815 // This variant of the method is used by the code which allocates or
2816 // renews leases. It may be the case that the lease has already been
2817 // reclaimed, so there is nothing to do.
2818 if (!lease->stateExpiredReclaimed()) {
2819 reclaimExpiredLease(lease, DB_RECLAIM_LEAVE_UNCHANGED, callout_handle);
2820 }
2821}
2822
2823void
2824AllocEngine::reclaimExpiredLease(const Lease6Ptr& lease,
2825 const DbReclaimMode& reclaim_mode,
2826 const CalloutHandlePtr& callout_handle) {
2827
2830 .arg(Pkt6::makeLabel(lease->duid_, lease->hwaddr_))
2831 .arg(lease->addr_.toText())
2832 .arg(static_cast<int>(lease->prefixlen_));
2833
2834 // The skip flag indicates if the callouts have taken responsibility
2835 // for reclaiming the lease. The callout will set this to true if
2836 // it reclaims the lease itself. In this case the reclamation routine
2837 // will not update DNS nor update the database.
2838 bool skipped = false;
2839 if (callout_handle) {
2840
2841 // Use the RAII wrapper to make sure that the callout handle state is
2842 // reset when this object goes out of scope. All hook points must do
2843 // it to prevent possible circular dependency between the callout
2844 // handle and its arguments.
2845 ScopedCalloutHandleState callout_handle_state(callout_handle);
2846
2847 callout_handle->deleteAllArguments();
2848 callout_handle->setArgument("lease6", lease);
2849 callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
2850
2851 HooksManager::callCallouts(Hooks.hook_index_lease6_expire_,
2852 *callout_handle);
2853
2854 skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
2855 }
2856
2859
2860 if (!skipped) {
2861
2862 // Generate removal name change request for D2, if required.
2863 // This will return immediately if the DNS wasn't updated
2864 // when the lease was created.
2865 queueNCR(CHG_REMOVE, lease);
2866
2867 // Let's check if the lease that just expired is in DECLINED state.
2868 // If it is, we need to perform a couple extra steps.
2869 bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
2870 if (lease->state_ == Lease::STATE_DECLINED) {
2871 // Do extra steps required for declined lease reclamation:
2872 // - call the recover hook
2873 // - bump decline-related stats
2874 // - log separate message
2875 // There's no point in keeping a declined lease after its
2876 // reclamation. A declined lease doesn't have any client
2877 // identifying information anymore. So we'll flag it for
2878 // removal unless the hook has set the skip flag.
2879 remove_lease = reclaimDeclined(lease);
2880 }
2881
2882 if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
2883 // Reclaim the lease - depending on the configuration, set the
2884 // expired-reclaimed state or simply remove it.
2885 LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2886 reclaimLeaseInDatabase<Lease6Ptr>(lease, remove_lease,
2887 std::bind(&LeaseMgr::updateLease6,
2888 &lease_mgr, ph::_1));
2889 }
2890 }
2891
2892 // Update statistics.
2893
2894 // Decrease number of assigned leases.
2895 if (lease->type_ == Lease::TYPE_NA) {
2896 // IA_NA
2897 StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2898 lease->subnet_id_,
2899 "assigned-nas"),
2900 static_cast<int64_t>(-1));
2901
2902 const auto& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getBySubnetId(lease->subnet_id_);
2903 if (subnet) {
2904 const auto& pool = subnet->getPool(lease->type_, lease->addr_, false);
2905 if (pool) {
2906 StatsMgr::instance().addValue(
2907 StatsMgr::generateName("subnet", subnet->getID(),
2908 StatsMgr::generateName("pool" , pool->getID(),
2909 "assigned-nas")),
2910 static_cast<int64_t>(-1));
2911
2912 StatsMgr::instance().addValue(
2913 StatsMgr::generateName("subnet", subnet->getID(),
2914 StatsMgr::generateName("pool" , pool->getID(),
2915 "reclaimed-leases")),
2916 static_cast<int64_t>(1));
2917 }
2918 }
2919
2920 } else if (lease->type_ == Lease::TYPE_PD) {
2921 // IA_PD
2922 StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2923 lease->subnet_id_,
2924 "assigned-pds"),
2925 static_cast<int64_t>(-1));
2926
2927 const auto& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getBySubnetId(lease->subnet_id_);
2928 if (subnet) {
2929 const auto& pool = subnet->getPool(lease->type_, lease->addr_, false);
2930 if (pool) {
2931 StatsMgr::instance().addValue(
2932 StatsMgr::generateName("subnet", subnet->getID(),
2933 StatsMgr::generateName("pd-pool" , pool->getID(),
2934 "assigned-pds")),
2935 static_cast<int64_t>(-1));
2936
2937 StatsMgr::instance().addValue(
2938 StatsMgr::generateName("subnet", subnet->getID(),
2939 StatsMgr::generateName("pd-pool" , pool->getID(),
2940 "reclaimed-leases")),
2941 static_cast<int64_t>(1));
2942 }
2943 }
2944 }
2945
2946 // Increase number of reclaimed leases for a subnet.
2947 StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2948 lease->subnet_id_,
2949 "reclaimed-leases"),
2950 static_cast<int64_t>(1));
2951
2952 // Increase total number of reclaimed leases.
2953 StatsMgr::instance().addValue("reclaimed-leases", static_cast<int64_t>(1));
2954}
2955
2956void
2957AllocEngine::reclaimExpiredLease(const Lease4Ptr& lease,
2958 const DbReclaimMode& reclaim_mode,
2959 const CalloutHandlePtr& callout_handle) {
2960
2963 .arg(Pkt4::makeLabel(lease->hwaddr_, lease->client_id_))
2964 .arg(lease->addr_.toText());
2965
2966 // The skip flag indicates if the callouts have taken responsibility
2967 // for reclaiming the lease. The callout will set this to true if
2968 // it reclaims the lease itself. In this case the reclamation routine
2969 // will not update DNS nor update the database.
2970 bool skipped = false;
2971 if (callout_handle) {
2972
2973 // Use the RAII wrapper to make sure that the callout handle state is
2974 // reset when this object goes out of scope. All hook points must do
2975 // it to prevent possible circular dependency between the callout
2976 // handle and its arguments.
2977 ScopedCalloutHandleState callout_handle_state(callout_handle);
2978
2979 callout_handle->setArgument("lease4", lease);
2980 callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
2981
2982 HooksManager::callCallouts(Hooks.hook_index_lease4_expire_,
2983 *callout_handle);
2984
2985 skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
2986 }
2987
2990
2991 if (!skipped) {
2992
2993 // Generate removal name change request for D2, if required.
2994 // This will return immediately if the DNS wasn't updated
2995 // when the lease was created.
2996 queueNCR(CHG_REMOVE, lease);
2997 // Clear DNS fields so we avoid redundant removes.
2998 lease->hostname_.clear();
2999 lease->fqdn_fwd_ = false;
3000 lease->fqdn_rev_ = false;
3001
3002 // Let's check if the lease that just expired is in DECLINED state.
3003 // If it is, we need to perform a couple extra steps.
3004 bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
3005 if (lease->state_ == Lease::STATE_DECLINED) {
3006 // Do extra steps required for declined lease reclamation:
3007 // - call the recover hook
3008 // - bump decline-related stats
3009 // - log separate message
3010 // There's no point in keeping a declined lease after its
3011 // reclamation. A declined lease doesn't have any client
3012 // identifying information anymore. So we'll flag it for
3013 // removal unless the hook has set the skip flag.
3014 remove_lease = reclaimDeclined(lease);
3015 }
3016
3017 if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
3018 // Reclaim the lease - depending on the configuration, set the
3019 // expired-reclaimed state or simply remove it.
3020 LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
3021 reclaimLeaseInDatabase<Lease4Ptr>(lease, remove_lease,
3022 std::bind(&LeaseMgr::updateLease4,
3023 &lease_mgr, ph::_1));
3024 }
3025 }
3026
3027 // Update statistics.
3028
3029 // Decrease number of assigned addresses.
3030 StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
3031 lease->subnet_id_,
3032 "assigned-addresses"),
3033 static_cast<int64_t>(-1));
3034
3035 // Increase number of reclaimed leases for a subnet.
3036 StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
3037 lease->subnet_id_,
3038 "reclaimed-leases"),
3039 static_cast<int64_t>(1));
3040
3041 const auto& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(lease->subnet_id_);
3042 if (subnet) {
3043 const auto& pool = subnet->getPool(Lease::TYPE_V4, lease->addr_, false);
3044 if (pool) {
3045 StatsMgr::instance().addValue(
3046 StatsMgr::generateName("subnet", subnet->getID(),
3047 StatsMgr::generateName("pool" , pool->getID(),
3048 "assigned-addresses")),
3049 static_cast<int64_t>(-1));
3050
3051 StatsMgr::instance().addValue(
3052 StatsMgr::generateName("subnet", subnet->getID(),
3053 StatsMgr::generateName("pool" , pool->getID(),
3054 "reclaimed-leases")),
3055 static_cast<int64_t>(1));
3056 }
3057 }
3058
3059 // Increase total number of reclaimed leases.
3060 StatsMgr::instance().addValue("reclaimed-leases", static_cast<int64_t>(1));
3061}
3062
3063void
3067 .arg(secs);
3068
3069 uint64_t deleted_leases = 0;
3070 try {
3071 // Try to delete leases from the lease database.
3072 LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
3073 deleted_leases = lease_mgr.deleteExpiredReclaimedLeases4(secs);
3074
3075 } catch (const std::exception& ex) {
3077 .arg(ex.what());
3078 }
3079
3082 .arg(deleted_leases);
3083}
3084
3085bool
3086AllocEngine::reclaimDeclined(const Lease4Ptr& lease) {
3087 if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
3088 return (true);
3089 }
3090
3091 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_recover_)) {
3092 CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
3093
3094 // Use the RAII wrapper to make sure that the callout handle state is
3095 // reset when this object goes out of scope. All hook points must do
3096 // it to prevent possible circular dependency between the callout
3097 // handle and its arguments.
3098 ScopedCalloutHandleState callout_handle_state(callout_handle);
3099
3100 // Pass necessary arguments
3101 callout_handle->setArgument("lease4", lease);
3102
3103 // Call the callouts
3104 HooksManager::callCallouts(Hooks.hook_index_lease4_recover_, *callout_handle);
3105
3106 // Callouts decided to skip the action. This means that the lease is not
3107 // assigned, so the client will get NoAddrAvail as a result. The lease
3108 // won't be inserted into the database.
3109 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
3111 .arg(lease->addr_.toText());
3112 return (false);
3113 }
3114 }
3115
3117 .arg(lease->addr_.toText())
3118 .arg(lease->valid_lft_);
3119
3120 StatsMgr& stats_mgr = StatsMgr::instance();
3121
3122 // Decrease subnet specific counter for currently declined addresses
3123 stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
3124 "declined-addresses"),
3125 static_cast<int64_t>(-1));
3126
3127 stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
3128 "reclaimed-declined-addresses"),
3129 static_cast<int64_t>(1));
3130
3131 const auto& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(lease->subnet_id_);
3132 if (subnet) {
3133 const auto& pool = subnet->getPool(Lease::TYPE_V4, lease->addr_, false);
3134 if (pool) {
3135 stats_mgr.addValue(StatsMgr::generateName("subnet", subnet->getID(),
3136 StatsMgr::generateName("pool" , pool->getID(),
3137 "declined-addresses")),
3138 static_cast<int64_t>(-1));
3139
3140 stats_mgr.addValue(StatsMgr::generateName("subnet", subnet->getID(),
3141 StatsMgr::generateName("pool" , pool->getID(),
3142 "reclaimed-declined-addresses")),
3143 static_cast<int64_t>(1));
3144 }
3145 }
3146
3147 // Decrease global counter for declined addresses
3148 stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
3149
3150 stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
3151
3152 // Note that we do not touch assigned-addresses counters. Those are
3153 // modified in whatever code calls this method.
3154 return (true);
3155}
3156
3157bool
3158AllocEngine::reclaimDeclined(const Lease6Ptr& lease) {
3159 if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
3160 return (true);
3161 }
3162
3163 if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_recover_)) {
3164 CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
3165
3166 // Use the RAII wrapper to make sure that the callout handle state is
3167 // reset when this object goes out of scope. All hook points must do
3168 // it to prevent possible circular dependency between the callout
3169 // handle and its arguments.
3170 ScopedCalloutHandleState callout_handle_state(callout_handle);
3171
3172 // Pass necessary arguments
3173 callout_handle->setArgument("lease6", lease);
3174
3175 // Call the callouts
3176 HooksManager::callCallouts(Hooks.hook_index_lease6_recover_, *callout_handle);
3177
3178 // Callouts decided to skip the action. This means that the lease is not
3179 // assigned, so the client will get NoAddrAvail as a result. The lease
3180 // won't be inserted into the database.
3181 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
3183 .arg(lease->addr_.toText());
3184 return (false);
3185 }
3186 }
3187
3189 .arg(lease->addr_.toText())
3190 .arg(lease->valid_lft_);
3191
3192 StatsMgr& stats_mgr = StatsMgr::instance();
3193
3194 // Decrease subnet specific counter for currently declined addresses
3195 stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
3196 "declined-addresses"),
3197 static_cast<int64_t>(-1));
3198
3199 stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
3200 "reclaimed-declined-addresses"),
3201 static_cast<int64_t>(1));
3202
3203 const auto& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getBySubnetId(lease->subnet_id_);
3204 if (subnet) {
3205 const auto& pool = subnet->getPool(lease->type_, lease->addr_, false);
3206 if (pool) {
3207 stats_mgr.addValue(StatsMgr::generateName("subnet", subnet->getID(),
3208 StatsMgr::generateName("pool" , pool->getID(),
3209 "declined-addresses")),
3210 static_cast<int64_t>(-1));
3211
3212 stats_mgr.addValue(StatsMgr::generateName("subnet", subnet->getID(),
3213 StatsMgr::generateName("pool" , pool->getID(),
3214 "reclaimed-declined-addresses")),
3215 static_cast<int64_t>(1));
3216 }
3217 }
3218
3219 // Decrease global counter for declined addresses
3220 stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
3221
3222 stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
3223
3224 // Note that we do not touch assigned-nas counters. Those are
3225 // modified in whatever code calls this method.
3226
3227 return (true);
3228}
3229
3230void
3232 lease->relay_id_.clear();
3233 lease->remote_id_.clear();
3234 if (lease->getContext()) {
3235 lease->setContext(ElementPtr());
3236 }
3237}
3238
3239void
3241 if (lease->getContext()) {
3242 lease->extended_info_action_ = Lease6::ACTION_DELETE;
3243 lease->setContext(ElementPtr());
3244 }
3245}
3246
3247template<typename LeasePtrType>
3248void AllocEngine::reclaimLeaseInDatabase(const LeasePtrType& lease,
3249 const bool remove_lease,
3250 const std::function<void (const LeasePtrType&)>&
3251 lease_update_fun) const {
3252
3253 LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
3254
3255 // Reclaim the lease - depending on the configuration, set the
3256 // expired-reclaimed state or simply remove it.
3257 if (remove_lease) {
3258 lease_mgr.deleteLease(lease);
3259 } else if (lease_update_fun) {
3260 // Clear FQDN information as we have already sent the
3261 // name change request to remove the DNS record.
3262 lease->reuseable_valid_lft_ = 0;
3263 lease->hostname_.clear();
3264 lease->fqdn_fwd_ = false;
3265 lease->fqdn_rev_ = false;
3266 lease->state_ = Lease::STATE_EXPIRED_RECLAIMED;
3268 lease_update_fun(lease);
3269
3270 } else {
3271 return;
3272 }
3273
3274 // Lease has been reclaimed.
3277 .arg(lease->addr_.toText());
3278}
3279
3280std::string
3282 if (!subnet) {
3283 return("<empty subnet>");
3284 }
3285
3286 SharedNetwork4Ptr network;
3287 subnet->getSharedNetwork(network);
3288 std::ostringstream ss;
3289 if (network) {
3290 ss << "shared-network: " << network->getName();
3291 } else {
3292 ss << "subnet id: " << subnet->getID();
3293 }
3294
3295 return(ss.str());
3296}
3297
3298} // namespace dhcp
3299} // namespace isc
3300
3301// ##########################################################################
3302// # DHCPv4 lease allocation code starts here.
3303// ##########################################################################
3304
3305namespace {
3306
3324bool
3325addressReserved(const IOAddress& address, const AllocEngine::ClientContext4& ctx) {
3326 // When out-of-pool flag is true the server may assume that all host
3327 // reservations are for addresses that do not belong to the dynamic pool.
3328 // Therefore, it can skip the reservation checks when dealing with in-pool
3329 // addresses.
3330 if (ctx.subnet_ && ctx.subnet_->getReservationsInSubnet() &&
3331 (!ctx.subnet_->getReservationsOutOfPool() ||
3332 !ctx.subnet_->inPool(Lease::TYPE_V4, address))) {
3333 // The global parameter ip-reservations-unique controls whether it is allowed
3334 // to specify multiple reservations for the same IP address or delegated prefix
3335 // or IP reservations must be unique. Some host backends do not support the
3336 // former, thus we can't always use getAll4 calls to get the reservations
3337 // for the given IP. When we're in the default mode, when IP reservations
3338 // are unique, we should call get4 (supported by all backends). If we're in
3339 // the mode in which non-unique reservations are allowed the backends which
3340 // don't support it are not used and we can safely call getAll4.
3341 ConstHostCollection hosts;
3342 if (CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getIPReservationsUnique()) {
3343 // Reservations are unique. It is safe to call get4 to get the unique host.
3344 ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(), address);
3345 if (host) {
3346 hosts.push_back(host);
3347 }
3348 } else {
3349 // Reservations can be non-unique. Need to get all reservations for that address.
3350 hosts = HostMgr::instance().getAll4(ctx.subnet_->getID(), address);
3351 }
3352
3353 for (auto host : hosts) {
3354 for (const AllocEngine::IdentifierPair& id_pair : ctx.host_identifiers_) {
3355 // If we find the matching host we know that this address is reserved
3356 // for us and we can return immediately.
3357 if (id_pair.first == host->getIdentifierType() &&
3358 id_pair.second == host->getIdentifier()) {
3359 return (false);
3360 }
3361 }
3362 }
3363 // We didn't find a matching host. If there are any reservations it means that
3364 // address is reserved for another client or multiple clients. If there are
3365 // no reservations address is not reserved for another client.
3366 return (!hosts.empty());
3367 }
3368 return (false);
3369}
3370
3386bool
3387hasAddressReservation(AllocEngine::ClientContext4& ctx) {
3388 if (ctx.hosts_.empty()) {
3389 return (false);
3390 }
3391
3392 // Fetch the globally reserved address if there is one.
3393 auto global_host = ctx.hosts_.find(SUBNET_ID_GLOBAL);
3394 auto global_host_address = ((global_host != ctx.hosts_.end() && global_host->second) ?
3395 global_host->second->getIPv4Reservation() :
3397
3398 // Start with currently selected subnet.
3399 Subnet4Ptr subnet = ctx.subnet_;
3400 while (subnet) {
3401 // If global reservations are enabled for this subnet and there is
3402 // globally reserved address and that address is feasible for this
3403 // subnet, update the selected subnet and return true.
3404 if (subnet->getReservationsGlobal() &&
3405 (global_host_address != IOAddress::IPV4_ZERO_ADDRESS()) &&
3406 (subnet->inRange(global_host_address))) {
3407 ctx.subnet_ = subnet;
3408 return (true);
3409 }
3410
3411 if (subnet->getReservationsInSubnet()) {
3412 auto host = ctx.hosts_.find(subnet->getID());
3413 // The out-of-pool flag indicates that no client should be assigned
3414 // reserved addresses from within the dynamic pool, and for that
3415 // reason look only for reservations that are outside the pools,
3416 // hence the inPool check.
3417 if (host != ctx.hosts_.end() && host->second) {
3418 auto reservation = host->second->getIPv4Reservation();
3419 if (!reservation.isV4Zero() &&
3420 (!subnet->getReservationsOutOfPool() ||
3421 !subnet->inPool(Lease::TYPE_V4, reservation))) {
3422 ctx.subnet_ = subnet;
3423 return (true);
3424 }
3425 }
3426 }
3427
3428 // No address reservation found here, so let's try another subnet
3429 // within the same shared network.
3430 subnet = subnet->getNextSubnet(ctx.subnet_, ctx.query_->getClasses());
3431 }
3432
3433 if (global_host_address != IOAddress::IPV4_ZERO_ADDRESS()) {
3436 .arg(ctx.currentHost()->getIPv4Reservation().toText())
3438 }
3439
3440 return (false);
3441}
3442
3458void findClientLease(AllocEngine::ClientContext4& ctx, Lease4Ptr& client_lease) {
3459 LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
3460
3461 Subnet4Ptr original_subnet = ctx.subnet_;
3462
3463 auto const& classes = ctx.query_->getClasses();
3464
3465 // Client identifier is optional. First check if we can try to lookup
3466 // by client-id.
3467 bool try_clientid_lookup = (ctx.clientid_ &&
3468 SharedNetwork4::subnetsIncludeMatchClientId(original_subnet, classes));
3469
3470 // If it is possible to use client identifier to try to find client's lease.
3471 if (try_clientid_lookup) {
3472 // Get all leases for this client identifier. When shared networks are
3473 // in use it is more efficient to make a single query rather than
3474 // multiple queries, one for each subnet.
3475 Lease4Collection leases_client_id = lease_mgr.getLease4(*ctx.clientid_);
3476
3477 // Iterate over the subnets within the shared network to see if any client's
3478 // lease belongs to them.
3479 for (Subnet4Ptr subnet = original_subnet; subnet;
3480 subnet = subnet->getNextSubnet(original_subnet, classes)) {
3481
3482 // If client identifier has been supplied and the server wasn't
3483 // explicitly configured to ignore client identifiers for this subnet
3484 // check if there is a lease within this subnet.
3485 if (subnet->getMatchClientId()) {
3486 for (auto l = leases_client_id.begin(); l != leases_client_id.end(); ++l) {
3487 if ((*l)->subnet_id_ == subnet->getID()) {
3488 // Lease found, so stick to this lease.
3489 client_lease = (*l);
3490 ctx.subnet_ = subnet;
3491 return;
3492 }
3493 }
3494 }
3495 }
3496 }
3497
3498 // If no lease found using the client identifier, try the lookup using
3499 // the HW address.
3500 if (!client_lease && ctx.hwaddr_) {
3501
3502 // Get all leases for this HW address.
3503 Lease4Collection leases_hw_address = lease_mgr.getLease4(*ctx.hwaddr_);
3504
3505 for (Subnet4Ptr subnet = original_subnet; subnet;
3506 subnet = subnet->getNextSubnet(original_subnet, classes)) {
3507 ClientIdPtr client_id;
3508 if (subnet->getMatchClientId()) {
3509 client_id = ctx.clientid_;
3510 }
3511
3512 // Try to find the lease that matches current subnet and belongs to
3513 // this client, so both HW address and client identifier match.
3514 for (Lease4Collection::const_iterator client_lease_it = leases_hw_address.begin();
3515 client_lease_it != leases_hw_address.end(); ++client_lease_it) {
3516 Lease4Ptr existing_lease = *client_lease_it;
3517 if ((existing_lease->subnet_id_ == subnet->getID()) &&
3518 existing_lease->belongsToClient(ctx.hwaddr_, client_id)) {
3519 // Found the lease of this client, so return it.
3520 client_lease = existing_lease;
3521 // We got a lease but the subnet it belongs to may differ from
3522 // the original subnet. Let's now stick to this subnet.
3523 ctx.subnet_ = subnet;
3524 return;
3525 }
3526 }
3527 }
3528 }
3529}
3530
3543bool
3544inAllowedPool(AllocEngine::ClientContext4& ctx, const IOAddress& address) {
3545 // If the subnet belongs to a shared network we will be iterating
3546 // over the subnets that belong to this shared network.
3547 Subnet4Ptr current_subnet = ctx.subnet_;
3548 auto const& classes = ctx.query_->getClasses();
3549
3550 while (current_subnet) {
3551 if (current_subnet->inPool(Lease::TYPE_V4, address, classes)) {
3552 // We found a subnet that this address belongs to, so it
3553 // seems that this subnet is the good candidate for allocation.
3554 // Let's update the selected subnet.
3555 ctx.subnet_ = current_subnet;
3556 return (true);
3557 }
3558
3559 current_subnet = current_subnet->getNextSubnet(ctx.subnet_, classes);
3560 }
3561
3562 return (false);
3563}
3564
3565} // namespace
3566
3567namespace isc {
3568namespace dhcp {
3569
3571 : early_global_reservations_lookup_(false),
3572 subnet_(), clientid_(), hwaddr_(),
3573 requested_address_(IOAddress::IPV4_ZERO_ADDRESS()),
3574 fwd_dns_update_(false), rev_dns_update_(false),
3575 hostname_(""), callout_handle_(), fake_allocation_(false), offer_lft_(0),
3576 old_lease_(), new_lease_(), hosts_(), conflicting_lease_(),
3577 query_(), host_identifiers_(), unknown_requested_addr_(false),
3578 ddns_params_() {
3579
3580}
3581
3583 const ClientIdPtr& clientid,
3584 const HWAddrPtr& hwaddr,
3585 const asiolink::IOAddress& requested_addr,
3586 const bool fwd_dns_update,
3587 const bool rev_dns_update,
3588 const std::string& hostname,
3589 const bool fake_allocation,
3590 const uint32_t offer_lft)
3591 : early_global_reservations_lookup_(false),
3592 subnet_(subnet), clientid_(clientid), hwaddr_(hwaddr),
3593 requested_address_(requested_addr),
3594 fwd_dns_update_(fwd_dns_update), rev_dns_update_(rev_dns_update),
3595 hostname_(hostname), callout_handle_(),
3596 fake_allocation_(fake_allocation), offer_lft_(offer_lft), old_lease_(), new_lease_(),
3597 hosts_(), host_identifiers_(), unknown_requested_addr_(false),
3598 ddns_params_(new DdnsParams()) {
3599
3600 // Initialize host identifiers.
3601 if (hwaddr) {
3602 addHostIdentifier(Host::IDENT_HWADDR, hwaddr->hwaddr_);
3603 }
3604}
3605
3608 if (subnet_ && subnet_->getReservationsInSubnet()) {
3609 auto host = hosts_.find(subnet_->getID());
3610 if (host != hosts_.cend()) {
3611 return (host->second);
3612 }
3613 }
3614
3615 return (globalHost());
3616}
3617
3620 if (subnet_ && subnet_->getReservationsGlobal()) {
3621 auto host = hosts_.find(SUBNET_ID_GLOBAL);
3622 if (host != hosts_.cend()) {
3623 return (host->second);
3624 }
3625 }
3626
3627 return (ConstHostPtr());
3628}
3629
3632 // We already have it return it unless the context subnet has changed.
3633 if (ddns_params_ && subnet_ && (subnet_->getID() == ddns_params_->getSubnetId())) {
3634 return (ddns_params_);
3635 }
3636
3637 // Doesn't exist yet or is stale, (re)create it.
3638 if (subnet_) {
3639 ddns_params_ = CfgMgr::instance().getCurrentCfg()->getDdnsParams(subnet_);
3640 return (ddns_params_);
3641 }
3642
3643 // Asked for it without a subnet? This case really shouldn't occur but
3644 // for now let's return an instance with default values.
3645 return (DdnsParamsPtr(new DdnsParams()));
3646}
3647
3650 // The NULL pointer indicates that the old lease didn't exist. It may
3651 // be later set to non NULL value if existing lease is found in the
3652 // database.
3653 ctx.old_lease_.reset();
3654 ctx.new_lease_.reset();
3655
3656 // Before we start allocation process, we need to make sure that the
3657 // selected subnet is allowed for this client. If not, we'll try to
3658 // use some other subnet within the shared network. If there are no
3659 // subnets allowed for this client within the shared network, we
3660 // can't allocate a lease.
3661 Subnet4Ptr subnet = ctx.subnet_;
3662 auto const& classes = ctx.query_->getClasses();
3663 if (subnet && !subnet->clientSupported(classes)) {
3664 ctx.subnet_ = subnet->getNextSubnet(subnet, classes);
3665 }
3666
3667 try {
3668 if (!ctx.subnet_) {
3669 isc_throw(BadValue, "Can't allocate IPv4 address without subnet");
3670 }
3671
3672 if (!ctx.hwaddr_) {
3673 isc_throw(BadValue, "HWAddr must be defined");
3674 }
3675
3676 if (ctx.fake_allocation_) {
3677 ctx.new_lease_ = discoverLease4(ctx);
3678 } else {
3679 ctx.new_lease_ = requestLease4(ctx);
3680 }
3681
3682 } catch (const isc::Exception& e) {
3683 // Some other error, return an empty lease.
3685 .arg(ctx.query_->getLabel())
3686 .arg(e.what());
3687 }
3688
3689 return (ctx.new_lease_);
3690}
3691
3692void
3694 // If there is no subnet, there is nothing to do.
3695 if (!ctx.subnet_) {
3696 return;
3697 }
3698
3699 auto subnet = ctx.subnet_;
3700
3701 // If already done just return.
3703 !subnet->getReservationsInSubnet()) {
3704 return;
3705 }
3706
3707 // @todo: This code can be trivially optimized.
3709 subnet->getReservationsGlobal()) {
3711 if (ghost) {
3712 ctx.hosts_[SUBNET_ID_GLOBAL] = ghost;
3713
3714 // If we had only to fetch global reservations it is done.
3715 if (!subnet->getReservationsInSubnet()) {
3716 return;
3717 }
3718 }
3719 }
3720
3721 std::map<SubnetID, ConstHostPtr> host_map;
3722 SharedNetwork4Ptr network;
3723 subnet->getSharedNetwork(network);
3724
3725 // If the subnet belongs to a shared network it is usually going to be
3726 // more efficient to make a query for all reservations for a particular
3727 // client rather than a query for each subnet within this shared network.
3728 // The only case when it is going to be less efficient is when there are
3729 // more host identifier types in use than subnets within a shared network.
3730 // As it breaks RADIUS use of host caching this can be disabled by the
3731 // host manager.
3732 const bool use_single_query = network &&
3734 (network->getAllSubnets()->size() > ctx.host_identifiers_.size());
3735
3736 if (use_single_query) {
3737 for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
3738 ConstHostCollection hosts = HostMgr::instance().getAll(id_pair.first,
3739 &id_pair.second[0],
3740 id_pair.second.size());
3741 // Store the hosts in the temporary map, because some hosts may
3742 // belong to subnets outside of the shared network. We'll need
3743 // to eliminate them.
3744 for (auto host = hosts.begin(); host != hosts.end(); ++host) {
3745 if ((*host)->getIPv4SubnetID() != SUBNET_ID_GLOBAL) {
3746 host_map[(*host)->getIPv4SubnetID()] = *host;
3747 }
3748 }
3749 }
3750 }
3751
3752 auto const& classes = ctx.query_->getClasses();
3753 // We can only search for the reservation if a subnet has been selected.
3754 while (subnet) {
3755
3756 // Only makes sense to get reservations if the client has access
3757 // to the class and host reservations are enabled for this subnet.
3758 if (subnet->clientSupported(classes) && subnet->getReservationsInSubnet()) {
3759 // Iterate over configured identifiers in the order of preference
3760 // and try to use each of them to search for the reservations.
3761 if (use_single_query) {
3762 if (host_map.count(subnet->getID()) > 0) {
3763 ctx.hosts_[subnet->getID()] = host_map[subnet->getID()];
3764 }
3765 } else {
3766 for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
3767 // Attempt to find a host using a specified identifier.
3768 ConstHostPtr host = HostMgr::instance().get4(subnet->getID(),
3769 id_pair.first,
3770 &id_pair.second[0],
3771 id_pair.second.size());
3772 // If we found matching host for this subnet.
3773 if (host) {
3774 ctx.hosts_[subnet->getID()] = host;
3775 break;
3776 }
3777 }
3778 }
3779 }
3780
3781 // We need to get to the next subnet if this is a shared network. If it
3782 // is not (a plain subnet), getNextSubnet will return NULL and we're
3783 // done here.
3784 subnet = subnet->getNextSubnet(ctx.subnet_, classes);
3785 }
3786
3787 // The hosts can be used by the server to return reserved options to
3788 // the DHCP client. Such options must be encapsulated (i.e., they must
3789 // include suboptions).
3790 for (auto host : ctx.hosts_) {
3791 host.second->encapsulateOptions();
3792 }
3793}
3794
3797 ConstHostPtr host;
3798 for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
3799 // Attempt to find a host using a specified identifier.
3800 host = HostMgr::instance().get4(SUBNET_ID_GLOBAL, id_pair.first,
3801 &id_pair.second[0], id_pair.second.size());
3802
3803 // If we found matching global host we're done.
3804 if (host) {
3805 break;
3806 }
3807 }
3808
3809 return (host);
3810}
3811
3813AllocEngine::discoverLease4(AllocEngine::ClientContext4& ctx) {
3814 // Find an existing lease for this client. This function will return null
3815 // if there is a conflict with existing lease and the allocation should
3816 // not be continued.
3817 Lease4Ptr client_lease;
3818 findClientLease(ctx, client_lease);
3819
3820 // Fetch offer_lft to see if we're allocating on DISCOVER.
3821 ctx.offer_lft_ = getOfferLft(ctx);
3822
3823 // new_lease will hold the pointer to the lease that we will offer to the
3824 // caller.
3825 Lease4Ptr new_lease;
3826
3827 CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
3828
3829 // Check if there is a reservation for the client. If there is, we want to
3830 // assign the reserved address, rather than any other one.
3831 if (hasAddressReservation(ctx)) {
3832
3835 .arg(ctx.query_->getLabel())
3836 .arg(ctx.currentHost()->getIPv4Reservation().toText());
3837
3838 // If the client doesn't have a lease or the leased address is different
3839 // than the reserved one then let's try to allocate the reserved address.
3840 // Otherwise the address that the client has is the one for which it
3841 // has a reservation, so just renew it.
3842 if (!client_lease || (client_lease->addr_ != ctx.currentHost()->getIPv4Reservation())) {
3843 // The call below will return a pointer to the lease for the address
3844 // reserved to this client, if the lease is available, i.e. is not
3845 // currently assigned to any other client.
3846 // Note that we don't remove the existing client's lease at this point
3847 // because this is not a real allocation, we just offer what we can
3848 // allocate in the DHCPREQUEST time.
3849 new_lease = allocateOrReuseLease4(ctx.currentHost()->getIPv4Reservation(), ctx,
3850 callout_status);
3851 if (!new_lease) {
3853 .arg(ctx.query_->getLabel())
3854 .arg(ctx.currentHost()->getIPv4Reservation().toText())
3855 .arg(ctx.conflicting_lease_ ? ctx.conflicting_lease_->toText() :
3856 "(no lease info)");
3857 StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
3858 ctx.conflicting_lease_->subnet_id_,
3859 "v4-reservation-conflicts"),
3860 static_cast<int64_t>(1));
3861 StatsMgr::instance().addValue("v4-reservation-conflicts",
3862 static_cast<int64_t>(1));
3863 }
3864
3865 } else {
3866 new_lease = renewLease4(client_lease, ctx);
3867 }
3868 }
3869
3870 // Client does not have a reservation or the allocation of the reserved
3871 // address has failed, probably because the reserved address is in use
3872 // by another client. If the client has a lease, we will check if we can
3873 // offer this lease to the client. The lease can't be offered in the
3874 // situation when it is reserved for another client or when the address
3875 // is not in the dynamic pool. The former may be the result of adding the
3876 // new reservation for the address used by this client. The latter may
3877 // be due to the client using the reserved out-of-the pool address, for
3878 // which the reservation has just been removed.
3879 if (!new_lease && client_lease && inAllowedPool(ctx, client_lease->addr_) &&
3880 !addressReserved(client_lease->addr_, ctx)) {
3881
3884 .arg(ctx.query_->getLabel());
3885
3886 // If offer-lifetime is shorter than the existing expiration, reset
3887 // offer-lifetime to zero. This allows us to simply return the
3888 // existing lease without updating it in the lease store.
3889 if ((ctx.offer_lft_) &&
3890 (time(NULL) + ctx.offer_lft_ < client_lease->getExpirationTime())) {
3891 ctx.offer_lft_ = 0;
3892 }
3893
3894 new_lease = renewLease4(client_lease, ctx);
3895 }
3896
3897 // The client doesn't have any lease or the lease can't be offered
3898 // because it is either reserved for some other client or the
3899 // address is not in the dynamic pool.
3900 // Let's use the client's hint (requested IP address), if the client
3901 // has provided it, and try to offer it. This address must not be
3902 // reserved for another client, and must be in the range of the
3903 // dynamic pool.
3904 if (!new_lease && !ctx.requested_address_.isV4Zero() &&
3905 inAllowedPool(ctx, ctx.requested_address_) &&
3906 !addressReserved(ctx.requested_address_, ctx)) {
3907
3910 .arg(ctx.requested_address_.toText())
3911 .arg(ctx.query_->getLabel());
3912
3913 new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx,
3914 callout_status);
3915 }
3916
3917 // The allocation engine failed to allocate all of the candidate
3918 // addresses. We will now use the allocator to pick the address
3919 // from the dynamic pool.
3920 if (!new_lease) {
3921
3924 .arg(ctx.query_->getLabel());
3925
3926 new_lease = allocateUnreservedLease4(ctx);
3927 }
3928
3929 // Some of the methods like reuseExpiredLease4 may set the old lease to point
3930 // to the lease which they remove/override. If it is not set, but we have
3931 // found that the client has the lease the client's lease is the one
3932 // to return as an old lease.
3933 if (!ctx.old_lease_ && client_lease) {
3934 ctx.old_lease_ = client_lease;
3935 }
3936
3937 return (new_lease);
3938}
3939
3941AllocEngine::requestLease4(AllocEngine::ClientContext4& ctx) {
3942 // Find an existing lease for this client. This function will return null
3943 // if there is a conflict with existing lease and the allocation should
3944 // not be continued.
3945 Lease4Ptr client_lease;
3946 findClientLease(ctx, client_lease);
3947
3948 // When the client sends the DHCPREQUEST, it should always specify the
3949 // address which it is requesting or renewing. That is, the client should
3950 // either use the requested IP address option or set the ciaddr. However,
3951 // we try to be liberal and allow the clients to not specify an address
3952 // in which case the allocation engine will pick a suitable address
3953 // for the client.
3954 if (!ctx.requested_address_.isV4Zero()) {
3955 // If the client has specified an address, make sure this address
3956 // is not reserved for another client. If it is, stop here because
3957 // we can't allocate this address.
3958 if (addressReserved(ctx.requested_address_, ctx)) {
3959
3962 .arg(ctx.query_->getLabel())
3963 .arg(ctx.requested_address_.toText());
3964
3965 return (Lease4Ptr());
3966 }
3967
3968 } else if (hasAddressReservation(ctx)) {
3969 // The client hasn't specified an address to allocate, so the
3970 // allocation engine needs to find an appropriate address.
3971 // If there is a reservation for the client, let's try to
3972 // allocate the reserved address.
3973 ctx.requested_address_ = ctx.currentHost()->getIPv4Reservation();
3974
3977 .arg(ctx.query_->getLabel())
3978 .arg(ctx.requested_address_.toText());
3979 }
3980
3981 if (!ctx.requested_address_.isV4Zero()) {
3982 // There is a specific address to be allocated. Let's find out if
3983 // the address is in use.
3985 // If the address is in use (allocated and not expired), we check
3986 // if the address is in use by our client or another client.
3987 // If it is in use by another client, the address can't be
3988 // allocated.
3989 if (existing && !existing->expired() &&
3990 !existing->belongsToClient(ctx.hwaddr_, ctx.subnet_->getMatchClientId() ?
3991 ctx.clientid_ : ClientIdPtr())) {
3992
3995 .arg(ctx.query_->getLabel())
3996 .arg(ctx.requested_address_.toText());
3997
3998 return (Lease4Ptr());
3999 }
4000
4001 // If the client has a reservation but it is requesting a different
4002 // address it is possible that the client was offered this different
4003 // address because the reserved address is in use. We will have to
4004 // check if the address is in use.
4005 if (hasAddressReservation(ctx) &&
4006 (ctx.currentHost()->getIPv4Reservation() != ctx.requested_address_)) {
4007 existing =
4008 LeaseMgrFactory::instance().getLease4(ctx.currentHost()->getIPv4Reservation());
4009 // If the reserved address is not in use, i.e. the lease doesn't
4010 // exist or is expired, and the client is requesting a different
4011 // address, return NULL. The client should go back to the
4012 // DHCPDISCOVER and the reserved address will be offered.
4013 if (!existing || existing->expired()) {
4014
4017 .arg(ctx.query_->getLabel())
4018 .arg(ctx.currentHost()->getIPv4Reservation().toText())
4019 .arg(ctx.requested_address_.toText());
4020
4021 return (Lease4Ptr());
4022 }
4023 }
4024
4025 // The use of the out-of-pool addresses is only allowed when the requested
4026 // address is reserved for the client. If the address is not reserved one
4027 // and it doesn't belong to the dynamic pool, do not allocate it.
4028 if ((!hasAddressReservation(ctx) ||
4029 (ctx.currentHost()->getIPv4Reservation() != ctx.requested_address_)) &&
4030 !inAllowedPool(ctx, ctx.requested_address_)) {
4031
4034 .arg(ctx.query_->getLabel())
4035 .arg(ctx.requested_address_);
4036
4037 ctx.unknown_requested_addr_ = true;
4038 return (Lease4Ptr());
4039 }
4040 }
4041
4042 // We have gone through all the checks, so we can now allocate the address
4043 // for the client.
4044
4045 // If the client is requesting an address which is assigned to the client
4046 // let's just renew this address. Also, renew this address if the client
4047 // doesn't request any specific address.
4048 // Added extra checks: the address is reserved for this client or belongs
4049 // to the dynamic pool for the case the pool class has changed before the
4050 // request.
4051 if (client_lease) {
4052 if (((client_lease->addr_ == ctx.requested_address_) ||
4054 ((hasAddressReservation(ctx) &&
4055 (ctx.currentHost()->getIPv4Reservation() == ctx.requested_address_)) ||
4056 inAllowedPool(ctx, client_lease->addr_))) {
4057
4060 .arg(ctx.query_->getLabel())
4061 .arg(ctx.requested_address_);
4062
4063 return (renewLease4(client_lease, ctx));
4064 }
4065 }
4066
4067 // new_lease will hold the pointer to the allocated lease if we allocate
4068 // successfully.
4069 Lease4Ptr new_lease;
4070
4071 // The client doesn't have the lease or it is requesting an address
4072 // which it doesn't have. Let's try to allocate the requested address.
4073 if (!ctx.requested_address_.isV4Zero()) {
4074
4077 .arg(ctx.query_->getLabel())
4078 .arg(ctx.requested_address_.toText());
4079
4080 // The call below will return a pointer to the lease allocated
4081 // for the client if there is no lease for the requested address,
4082 // or the existing lease has expired. If the allocation fails,
4083 // e.g. because the lease is in use, we will return NULL to
4084 // indicate that we were unable to allocate the lease.
4085 CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
4086 new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx,
4087 callout_status);
4088
4089 } else {
4090
4093 .arg(ctx.query_->getLabel());
4094
4095 // We will only get here if the client didn't specify which
4096 // address it wanted to be allocated. The allocation engine will
4097 // to pick the address from the dynamic pool.
4098 new_lease = allocateUnreservedLease4(ctx);
4099 }
4100
4101 // If we allocated the lease for the client, but the client already had a
4102 // lease, we will need to return the pointer to the previous lease and
4103 // the previous lease needs to be removed from the lease database.
4104 if (new_lease && client_lease) {
4105 ctx.old_lease_ = Lease4Ptr(new Lease4(*client_lease));
4106
4109 .arg(ctx.query_->getLabel())
4110 .arg(client_lease->addr_.toText());
4111
4112 if (LeaseMgrFactory::instance().deleteLease(client_lease)) {
4113 // Need to decrease statistic for assigned addresses.
4114 StatsMgr::instance().addValue(
4115 StatsMgr::generateName("subnet", client_lease->subnet_id_,
4116 "assigned-addresses"),
4117 static_cast<int64_t>(-1));
4118
4119 const auto& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(client_lease->subnet_id_);
4120 if (subnet) {
4121 const auto& pool = subnet->getPool(Lease::TYPE_V4, client_lease->addr_, false);
4122 if (pool) {
4123 StatsMgr::instance().addValue(
4124 StatsMgr::generateName("subnet", subnet->getID(),
4125 StatsMgr::generateName("pool", pool->getID(),
4126 "assigned-addresses")),
4127 static_cast<int64_t>(-1));
4128 }
4129 }
4130 }
4131 }
4132
4133 // Return the allocated lease or NULL pointer if allocation was
4134 // unsuccessful.
4135 return (new_lease);
4136}
4137
4138uint32_t
4140 // Not a DISCOVER or it's BOOTP, punt.
4141 if ((!ctx.fake_allocation_) || (ctx.query_->inClass("BOOTP"))) {
4142 return (0);
4143 }
4144
4145 util::Optional<uint32_t> offer_lft;
4146
4147 // If specified in one of our classes use it.
4148 // We use the first one we find.
4149 const ClientClasses classes = ctx.query_->getClasses();
4150 if (!classes.empty()) {
4151 // Let's get class definitions
4152 const ClientClassDictionaryPtr& dict =
4153 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
4154
4155 // Iterate over the assigned class definitions.
4156 for (ClientClasses::const_iterator name = classes.cbegin();
4157 name != classes.cend(); ++name) {
4158 ClientClassDefPtr cl = dict->findClass(*name);
4159 if (cl && (!cl->getOfferLft().unspecified())) {
4160 offer_lft = cl->getOfferLft();
4161 break;
4162 }
4163 }
4164 }
4165
4166 // If no classes specified it, get it from the subnet.
4167 if (offer_lft.unspecified()) {
4168 offer_lft = ctx.subnet_->getOfferLft();
4169 }
4170
4171 return (offer_lft.unspecified() ? 0 : offer_lft.get());
4172}
4173
4174uint32_t
4176 // If it's BOOTP, use infinite valid lifetime.
4177 if (ctx.query_->inClass("BOOTP")) {
4178 return (Lease::INFINITY_LFT);
4179 }
4180
4181 // Use the dhcp-lease-time content from the client if it's there.
4182 uint32_t requested_lft = 0;
4183 OptionPtr opt = ctx.query_->getOption(DHO_DHCP_LEASE_TIME);
4184 if (opt) {
4185 OptionUint32Ptr opt_lft = boost::dynamic_pointer_cast<OptionInt<uint32_t> >(opt);
4186 if (opt_lft) {
4187 requested_lft = opt_lft->getValue();
4188 }
4189 }
4190
4191 // If the triplet is specified in one of our classes use it.
4192 // We use the first one we find.
4193 Triplet<uint32_t> candidate_lft;
4194 const ClientClasses classes = ctx.query_->getClasses();
4195 if (!classes.empty()) {
4196 // Let's get class definitions
4197 const ClientClassDictionaryPtr& dict =
4198 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
4199
4200 // Iterate over the assigned class definitions.
4201 for (ClientClasses::const_iterator name = classes.cbegin();
4202 name != classes.cend(); ++name) {
4203 ClientClassDefPtr cl = dict->findClass(*name);
4204 if (cl && (!cl->getValid().unspecified())) {
4205 candidate_lft = cl->getValid();
4206 break;
4207 }
4208 }
4209 }
4210
4211 // If no classes specified it, get it from the subnet.
4212 if (!candidate_lft) {
4213 candidate_lft = ctx.subnet_->getValid();
4214 }
4215
4216 // If client requested a value, use the value bounded by
4217 // the candidate triplet.
4218 if (requested_lft > 0) {
4219 return (candidate_lft.get(requested_lft));
4220 }
4221
4222 // Use the candidate's default value.
4223 return (candidate_lft.get());
4224}
4225
4227AllocEngine::createLease4(const ClientContext4& ctx, const IOAddress& addr,
4228 CalloutHandle::CalloutNextStep& callout_status) {
4229 if (!ctx.hwaddr_) {
4230 isc_throw(BadValue, "Can't create a lease with NULL HW address");
4231 }
4232 if (!ctx.subnet_) {
4233 isc_throw(BadValue, "Can't create a lease without a subnet");
4234 }
4235
4236 // Get the context appropriate lifetime.
4237 uint32_t valid_lft = (ctx.offer_lft_ ? ctx.offer_lft_ : getValidLft(ctx));
4238
4239 time_t now = time(NULL);
4240
4241 ClientIdPtr client_id;
4242 if (ctx.subnet_->getMatchClientId()) {
4243 client_id = ctx.clientid_;
4244 }
4245
4246 Lease4Ptr lease(new Lease4(addr, ctx.hwaddr_, client_id,
4247 valid_lft, now, ctx.subnet_->getID()));
4248
4249 // Set FQDN specific lease parameters.
4250 lease->fqdn_fwd_ = ctx.fwd_dns_update_;
4251 lease->fqdn_rev_ = ctx.rev_dns_update_;
4252 lease->hostname_ = ctx.hostname_;
4253
4254 // Add (update) the extended information on the lease.
4255 static_cast<void>(updateLease4ExtendedInfo(lease, ctx));
4256
4257 // Let's execute all callouts registered for lease4_select
4258 if (ctx.callout_handle_ &&
4259 HooksManager::calloutsPresent(hook_index_lease4_select_)) {
4260
4261 // Use the RAII wrapper to make sure that the callout handle state is
4262 // reset when this object goes out of scope. All hook points must do
4263 // it to prevent possible circular dependency between the callout
4264 // handle and its arguments.
4265 ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
4266
4267 // Enable copying options from the packet within hook library.
4268 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
4269
4270 // Pass necessary arguments
4271 // Pass the original client query
4272 ctx.callout_handle_->setArgument("query4", ctx.query_);
4273
4274 // Subnet from which we do the allocation (That's as far as we can go
4275 // with using SubnetPtr to point to Subnet4 object. Users should not
4276 // be confused with dynamic_pointer_casts. They should get a concrete
4277 // pointer (Subnet4Ptr) pointing to a Subnet4 object.
4278 Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
4279 ctx.callout_handle_->setArgument("subnet4", subnet4);
4280
4281 // Is this solicit (fake = true) or request (fake = false)
4282 ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
4283
4284 // Are we allocating on DISCOVER? (i.e. offer_lft > 0).
4285 ctx.callout_handle_->setArgument("offer_lft", ctx.offer_lft_);
4286
4287 // Pass the intended lease as well
4288 ctx.callout_handle_->setArgument("lease4", lease);
4289
4290 // This is the first callout, so no need to clear any arguments
4291 HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
4292
4293 callout_status = ctx.callout_handle_->getStatus();
4294
4295 // Callouts decided to skip the action. This means that the lease is not
4296 // assigned, so the client will get NoAddrAvail as a result. The lease
4297 // won't be inserted into the database.
4298 if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
4300 return (Lease4Ptr());
4301 }
4302
4303 // Let's use whatever callout returned. Hopefully it is the same lease
4304 // we handled to it.
4305 ctx.callout_handle_->getArgument("lease4", lease);
4306 }
4307
4308 if (ctx.fake_allocation_ && ctx.offer_lft_) {
4309 // Turn them off before we persist, so we'll see it as different when
4310 // we extend it in the REQUEST. This should cause us to do DDNS (if
4311 // it's enabled).
4312 lease->fqdn_fwd_ = false;
4313 lease->fqdn_rev_ = false;
4314 }
4315
4316 if (!ctx.fake_allocation_ || ctx.offer_lft_) {
4317 const auto& pool = ctx.subnet_->getPool(Lease::TYPE_V4, lease->addr_, false);
4318 if (pool) {
4319 lease->pool_id_ = pool->getID();
4320 }
4321 // That is a real (REQUEST) allocation
4322 bool status = LeaseMgrFactory::instance().addLease(lease);
4323 if (status) {
4324
4325 // The lease insertion succeeded, let's bump up the statistic.
4326 StatsMgr::instance().addValue(
4327 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4328 "assigned-addresses"),
4329 static_cast<int64_t>(1));
4330
4331 StatsMgr::instance().addValue(
4332 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4333 "cumulative-assigned-addresses"),
4334 static_cast<int64_t>(1));
4335
4336 if (pool) {
4337 StatsMgr::instance().addValue(
4338 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4339 StatsMgr::generateName("pool", pool->getID(),
4340 "assigned-addresses")),
4341 static_cast<int64_t>(1));
4342
4343 StatsMgr::instance().addValue(
4344 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4345 StatsMgr::generateName("pool", pool->getID(),
4346 "cumulative-assigned-addresses")),
4347 static_cast<int64_t>(1));
4348 }
4349
4350 StatsMgr::instance().addValue("cumulative-assigned-addresses",
4351 static_cast<int64_t>(1));
4352
4353 return (lease);
4354 } else {
4355 // One of many failures with LeaseMgr (e.g. lost connection to the
4356 // database, database failed etc.). One notable case for that
4357 // is that we are working in multi-process mode and we lost a race
4358 // (some other process got that address first)
4359 return (Lease4Ptr());
4360 }
4361 } else {
4362 // That is only fake (DISCOVER) allocation
4363 // It is for OFFER only. We should not insert the lease and callers
4364 // have already verified the lease does not exist in the database.
4365 return (lease);
4366 }
4367}
4368
4370AllocEngine::renewLease4(const Lease4Ptr& lease,
4372 if (!lease) {
4373 isc_throw(BadValue, "null lease specified for renewLease4");
4374 }
4375
4376 // Let's keep the old data. This is essential if we are using memfile
4377 // (the lease returned points directly to the lease4 object in the database)
4378 // We'll need it if we want to skip update (i.e. roll back renewal)
4380 Lease4Ptr old_values = boost::make_shared<Lease4>(*lease);
4381 ctx.old_lease_.reset(new Lease4(*old_values));
4382
4383 // Update the lease with the information from the context.
4384 // If there was no significant changes, try reuse.
4385 lease->reuseable_valid_lft_ = 0;
4386 if (!updateLease4Information(lease, ctx)) {
4387 setLeaseReusable(lease, ctx);
4388 }
4389
4390 if (!ctx.fake_allocation_ || ctx.offer_lft_) {
4391 // If the lease is expired we have to reclaim it before
4392 // re-assigning it to the client. The lease reclamation
4393 // involves execution of hooks and DNS update.
4394 if (ctx.old_lease_->expired()) {
4395 reclaimExpiredLease(ctx.old_lease_, ctx.callout_handle_);
4396 }
4397
4398 lease->state_ = Lease::STATE_DEFAULT;
4399 }
4400
4401 bool skip = false;
4402 // Execute all callouts registered for lease4_renew.
4403 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_renew_)) {
4404
4405 // Use the RAII wrapper to make sure that the callout handle state is
4406 // reset when this object goes out of scope. All hook points must do
4407 // it to prevent possible circular dependency between the callout
4408 // handle and its arguments.
4409 ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
4410
4411 // Enable copying options from the packet within hook library.
4412 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
4413
4414 // Subnet from which we do the allocation. Convert the general subnet
4415 // pointer to a pointer to a Subnet4. Note that because we are using
4416 // boost smart pointers here, we need to do the cast using the boost
4417 // version of dynamic_pointer_cast.
4418 Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
4419
4420 // Pass the parameters. Note the clientid is passed only if match-client-id
4421 // is set. This is done that way, because the lease4-renew hook point is
4422 // about renewing a lease and the configuration parameter says the
4423 // client-id should be ignored. Hence no clientid value if match-client-id
4424 // is false.
4425 ctx.callout_handle_->setArgument("query4", ctx.query_);
4426 ctx.callout_handle_->setArgument("subnet4", subnet4);
4427 ctx.callout_handle_->setArgument("clientid", subnet4->getMatchClientId() ?
4428 ctx.clientid_ : ClientIdPtr());
4429 ctx.callout_handle_->setArgument("hwaddr", ctx.hwaddr_);
4430
4431 // Pass the lease to be updated
4432 ctx.callout_handle_->setArgument("lease4", lease);
4433
4434 // Call all installed callouts
4435 HooksManager::callCallouts(Hooks.hook_index_lease4_renew_,
4436 *ctx.callout_handle_);
4437
4438 // Callouts decided to skip the next processing step. The next
4439 // processing step would actually renew the lease, so skip at this
4440 // stage means "keep the old lease as it is".
4441 if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
4442 skip = true;
4445 }
4446
4448 }
4449
4450 if ((!ctx.fake_allocation_ || ctx.offer_lft_) && !skip && (lease->reuseable_valid_lft_ == 0)) {
4451 const auto& pool = ctx.subnet_->getPool(Lease::TYPE_V4, lease->addr_, false);
4452 if (pool) {
4453 lease->pool_id_ = pool->getID();
4454 }
4455
4456 // for REQUEST we do update the lease
4458
4459 // We need to account for the re-assignment of the lease.
4460 if (ctx.old_lease_->expired() || ctx.old_lease_->state_ == Lease::STATE_EXPIRED_RECLAIMED) {
4461 StatsMgr::instance().addValue(
4462 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4463 "assigned-addresses"),
4464 static_cast<int64_t>(1));
4465
4466 StatsMgr::instance().addValue(
4467 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4468 "cumulative-assigned-addresses"),
4469 static_cast<int64_t>(1));
4470
4471 if (pool) {
4472 StatsMgr::instance().addValue(
4473 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4474 StatsMgr::generateName("pool", pool->getID(),
4475 "assigned-addresses")),
4476 static_cast<int64_t>(1));
4477
4478 StatsMgr::instance().addValue(
4479 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4480 StatsMgr::generateName("pool", pool->getID(),
4481 "cumulative-assigned-addresses")),
4482 static_cast<int64_t>(1));
4483 }
4484
4485 StatsMgr::instance().addValue("cumulative-assigned-addresses",
4486 static_cast<int64_t>(1));
4487 }
4488 }
4489 if (skip) {
4490 // Rollback changes (really useful only for memfile)
4492 *lease = *old_values;
4493 }
4494
4495 return (lease);
4496}
4497
4499AllocEngine::reuseExpiredLease4(Lease4Ptr& expired,
4501 CalloutHandle::CalloutNextStep& callout_status) {
4502 if (!expired) {
4503 isc_throw(BadValue, "null lease specified for reuseExpiredLease");
4504 }
4505
4506 if (!ctx.subnet_) {
4507 isc_throw(BadValue, "null subnet specified for the reuseExpiredLease");
4508 }
4509
4510 if (!ctx.fake_allocation_ || ctx.offer_lft_) {
4511 // The expired lease needs to be reclaimed before it can be reused.
4512 // This includes declined leases for which probation period has
4513 // elapsed.
4514 reclaimExpiredLease(expired, ctx.callout_handle_);
4515 expired->state_ = Lease::STATE_DEFAULT;
4516 }
4517
4518 expired->reuseable_valid_lft_ = 0;
4519 static_cast<void>(updateLease4Information(expired, ctx));
4520
4523 .arg(ctx.query_->getLabel())
4524 .arg(expired->toText());
4525
4526 // Let's execute all callouts registered for lease4_select
4527 if (ctx.callout_handle_ &&
4528 HooksManager::calloutsPresent(hook_index_lease4_select_)) {
4529
4530 // Enable copying options from the packet within hook library.
4531 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
4532
4533 // Use the RAII wrapper to make sure that the callout handle state is
4534 // reset when this object goes out of scope. All hook points must do
4535 // it to prevent possible circular dependency between the callout
4536 // handle and its arguments.
4537 ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
4538
4539 // Pass necessary arguments
4540 // Pass the original client query
4541 ctx.callout_handle_->setArgument("query4", ctx.query_);
4542
4543 // Subnet from which we do the allocation. Convert the general subnet
4544 // pointer to a pointer to a Subnet4. Note that because we are using
4545 // boost smart pointers here, we need to do the cast using the boost
4546 // version of dynamic_pointer_cast.
4547 Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
4548 ctx.callout_handle_->setArgument("subnet4", subnet4);
4549
4550 // Is this solicit (fake = true) or request (fake = false)
4551 ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
4552 ctx.callout_handle_->setArgument("offer_lft", ctx.offer_lft_);
4553
4554 // The lease that will be assigned to a client
4555 ctx.callout_handle_->setArgument("lease4", expired);
4556
4557 // Call the callouts
4558 HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
4559
4560 callout_status = ctx.callout_handle_->getStatus();
4561
4562 // Callouts decided to skip the action. This means that the lease is not
4563 // assigned, so the client will get NoAddrAvail as a result. The lease
4564 // won't be inserted into the database.
4565 if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
4568 return (Lease4Ptr());
4569 }
4570
4572
4573 // Let's use whatever callout returned. Hopefully it is the same lease
4574 // we handed to it.
4575 ctx.callout_handle_->getArgument("lease4", expired);
4576 }
4577
4578 if (!ctx.fake_allocation_ || ctx.offer_lft_) {
4579 const auto& pool = ctx.subnet_->getPool(Lease::TYPE_V4, expired->addr_, false);
4580 if (pool) {
4581 expired->pool_id_ = pool->getID();
4582 }
4583 // for REQUEST we do update the lease
4585
4586 // We need to account for the re-assignment of the lease.
4587 StatsMgr::instance().addValue(
4588 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4589 "assigned-addresses"),
4590 static_cast<int64_t>(1));
4591
4592 StatsMgr::instance().addValue(
4593 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4594 "cumulative-assigned-addresses"),
4595 static_cast<int64_t>(1));
4596
4597 if (pool) {
4598 StatsMgr::instance().addValue(
4599 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4600 StatsMgr::generateName("pool", pool->getID(),
4601 "assigned-addresses")),
4602 static_cast<int64_t>(1));
4603
4604 StatsMgr::instance().addValue(
4605 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4606 StatsMgr::generateName("pool", pool->getID(),
4607 "cumulative-assigned-addresses")),
4608 static_cast<int64_t>(1));
4609 }
4610
4611 StatsMgr::instance().addValue("cumulative-assigned-addresses",
4612 static_cast<int64_t>(1));
4613 }
4614
4615 // We do nothing for SOLICIT. We'll just update database when
4616 // the client gets back to us with REQUEST message.
4617
4618 // it's not really expired at this stage anymore - let's return it as
4619 // an updated lease
4620 return (expired);
4621}
4622
4624AllocEngine::allocateOrReuseLease4(const IOAddress& candidate, ClientContext4& ctx,
4625 CalloutHandle::CalloutNextStep& callout_status) {
4626 ctx.conflicting_lease_.reset();
4627
4628 Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
4629 if (exist_lease) {
4630 if (exist_lease->expired()) {
4631 ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
4632 // reuseExpiredLease4() will reclaim the use which will
4633 // queue an NCR remove it needed. Clear the DNS fields in
4634 // the old lease to avoid a redundant remove in server logic.
4635 ctx.old_lease_->hostname_.clear();
4636 ctx.old_lease_->fqdn_fwd_ = false;
4637 ctx.old_lease_->fqdn_rev_ = false;
4638 return (reuseExpiredLease4(exist_lease, ctx, callout_status));
4639
4640 } else {
4641 // If there is a lease and it is not expired, pass this lease back
4642 // to the caller in the context. The caller may need to know
4643 // which lease we're conflicting with.
4644 ctx.conflicting_lease_ = exist_lease;
4645 }
4646
4647 } else {
4648 return (createLease4(ctx, candidate, callout_status));
4649 }
4650 return (Lease4Ptr());
4651}
4652
4654AllocEngine::allocateUnreservedLease4(ClientContext4& ctx) {
4655 Lease4Ptr new_lease;
4656 Subnet4Ptr subnet = ctx.subnet_;
4657
4658 // Need to check if the subnet belongs to a shared network. If so,
4659 // we might be able to find a better subnet for lease allocation,
4660 // for which it is more likely that there are some leases available.
4661 // If we stick to the selected subnet, we may end up walking over
4662 // the entire subnet (or more subnets) to discover that the address
4663 // pools have been exhausted. Using a subnet from which an address
4664 // was assigned most recently is an optimization which increases
4665 // the likelihood of starting from the subnet which address pools
4666 // are not exhausted.
4667 SharedNetwork4Ptr network;
4668 ctx.subnet_->getSharedNetwork(network);
4669 if (network) {
4670 // This would try to find a subnet with the same set of classes
4671 // as the current subnet, but with the more recent "usage timestamp".
4672 // This timestamp is only updated for the allocations made with an
4673 // allocator (unreserved lease allocations), not the static
4674 // allocations or requested addresses.
4675 ctx.subnet_ = subnet = network->getPreferredSubnet(ctx.subnet_);
4676 }
4677
4678 // We have the choice in the order checking the lease and
4679 // the reservation. The default is to begin by the lease
4680 // if the multi-threading is disabled.
4681 bool check_reservation_first = MultiThreadingMgr::instance().getMode();
4682
4683 Subnet4Ptr original_subnet = subnet;
4684
4685 uint128_t total_attempts = 0;
4686
4687 // The following counter tracks the number of subnets with matching client
4688 // classes from which the allocation engine attempted to assign leases.
4689 uint64_t subnets_with_unavail_leases = 0;
4690 // The following counter tracks the number of subnets in which there were
4691 // no matching pools for the client.
4692 uint64_t subnets_with_unavail_pools = 0;
4693
4694 auto const& classes = ctx.query_->getClasses();
4695
4696 while (subnet) {
4697 ClientIdPtr client_id;
4698 if (subnet->getMatchClientId()) {
4699 client_id = ctx.clientid_;
4700 }
4701
4702 uint128_t const possible_attempts =
4703 subnet->getPoolCapacity(Lease::TYPE_V4, classes);
4704
4705 // If the number of tries specified in the allocation engine constructor
4706 // is set to 0 (unlimited) or the pools capacity is lower than that number,
4707 // let's use the pools capacity as the maximum number of tries. Trying
4708 // more than the actual pools capacity is a waste of time. If the specified
4709 // number of tries is lower than the pools capacity, use that number.
4710 uint128_t const max_attempts =
4711 (attempts_ == 0 || possible_attempts < attempts_) ?
4712 possible_attempts :
4713 attempts_;
4714
4715 if (max_attempts > 0) {
4716 // If max_attempts is greater than 0, there are some pools in this subnet
4717 // from which we can potentially get a lease.
4718 ++subnets_with_unavail_leases;
4719 } else {
4720 // If max_attempts is 0, it is an indication that there are no pools
4721 // in the subnet from which we can get a lease.
4722 ++subnets_with_unavail_pools;
4723 }
4724
4725 bool exclude_first_last_24 = ((subnet->get().second <= 24) &&
4726 CfgMgr::instance().getCurrentCfg()->getExcludeFirstLast24());
4727
4728 CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
4729
4730 for (uint128_t i = 0; i < max_attempts; ++i) {
4731
4732 ++total_attempts;
4733
4734 auto allocator = subnet->getAllocator(Lease::TYPE_V4);
4735 IOAddress candidate = allocator->pickAddress(classes,
4736 client_id,
4737 ctx.requested_address_);
4738
4739 // An allocator may return zero address when it has pools exhausted.
4740 if (candidate.isV4Zero()) {
4741 break;
4742 }
4743
4744 if (exclude_first_last_24) {
4745 // Exclude .0 and .255 addresses.
4746 auto const& bytes = candidate.toBytes();
4747 if ((bytes.size() != 4) ||
4748 (bytes[3] == 0) || (bytes[3] == 255U)) {
4749 // Don't allocate.
4750 continue;
4751 }
4752 }
4753
4754 // First check for reservation when it is the choice.
4755 if (check_reservation_first && addressReserved(candidate, ctx)) {
4756 // Don't allocate.
4757 continue;
4758 }
4759
4760 // Check if the resource is busy i.e. can be being allocated
4761 // by another thread to another client.
4762 ResourceHandler4 resource_handler;
4763 if (MultiThreadingMgr::instance().getMode() &&
4764 !resource_handler.tryLock4(candidate)) {
4765 // Don't allocate.
4766 continue;
4767 }
4768
4769 // Check for an existing lease for the candidate address.
4770 Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
4771 if (!exist_lease) {
4772 // No existing lease, is it reserved?
4773 if (check_reservation_first || !addressReserved(candidate, ctx)) {
4774 // Not reserved use it.
4775 new_lease = createLease4(ctx, candidate, callout_status);
4776 }
4777 } else {
4778 // An lease exists, is expired, and not reserved use it.
4779 if (exist_lease->expired() &&
4780 (check_reservation_first || !addressReserved(candidate, ctx))) {
4781 ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
4782 new_lease = reuseExpiredLease4(exist_lease, ctx, callout_status);
4783 }
4784 }
4785
4786 // We found a lease we can use, return it.
4787 if (new_lease) {
4788 return (new_lease);
4789 }
4790
4791 if (ctx.callout_handle_ && (callout_status != CalloutHandle::NEXT_STEP_CONTINUE)) {
4792 // Don't retry when the callout status is not continue.
4793 subnet.reset();
4794 break;
4795 }
4796 }
4797
4798 // This pointer may be set to NULL if hooks set SKIP status.
4799 if (subnet) {
4800 subnet = subnet->getNextSubnet(original_subnet, classes);
4801
4802 if (subnet) {
4803 ctx.subnet_ = subnet;
4804 }
4805 }
4806 }
4807
4808 if (network) {
4809 // The client is in the shared network. Let's log the high level message
4810 // indicating which shared network the client belongs to.
4812 .arg(ctx.query_->getLabel())
4813 .arg(network->getName())
4814 .arg(subnets_with_unavail_leases)
4815 .arg(subnets_with_unavail_pools);
4816 StatsMgr::instance().addValue("v4-allocation-fail-shared-network",
4817 static_cast<int64_t>(1));
4818 StatsMgr::instance().addValue(
4819 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4820 "v4-allocation-fail-shared-network"),
4821 static_cast<int64_t>(1));
4822 } else {
4823 // The client is not connected to a shared network. It is connected
4824 // to a subnet. Let's log some details about the subnet.
4825 std::string shared_network = ctx.subnet_->getSharedNetworkName();
4826 if (shared_network.empty()) {
4827 shared_network = "(none)";
4828 }
4830 .arg(ctx.query_->getLabel())
4831 .arg(ctx.subnet_->toText())
4832 .arg(ctx.subnet_->getID())
4833 .arg(shared_network);
4834 StatsMgr::instance().addValue("v4-allocation-fail-subnet",
4835 static_cast<int64_t>(1));
4836 StatsMgr::instance().addValue(
4837 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4838 "v4-allocation-fail-subnet"),
4839 static_cast<int64_t>(1));
4840 }
4841 if (total_attempts == 0) {
4842 // In this case, it seems that none of the pools in the subnets could
4843 // be used for that client, both in case the client is connected to
4844 // a shared network or to a single subnet. Apparently, the client was
4845 // rejected to use the pools because of the client classes' mismatch.
4847 .arg(ctx.query_->getLabel());
4848 StatsMgr::instance().addValue("v4-allocation-fail-no-pools",
4849 static_cast<int64_t>(1));
4850 StatsMgr::instance().addValue(
4851 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4852 "v4-allocation-fail-no-pools"),
4853 static_cast<int64_t>(1));
4854 } else {
4855 // This is an old log message which provides a number of attempts
4856 // made by the allocation engine to allocate a lease. The only case
4857 // when we don't want to log this message is when the number of
4858 // attempts is zero (condition above), because it would look silly.
4860 .arg(ctx.query_->getLabel())
4861 .arg(total_attempts);
4862 StatsMgr::instance().addValue("v4-allocation-fail",
4863 static_cast<int64_t>(1));
4864 StatsMgr::instance().addValue(
4865 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4866 "v4-allocation-fail"),
4867 static_cast<int64_t>(1));
4868 }
4869
4870 if (!classes.empty()) {
4872 .arg(ctx.query_->getLabel())
4873 .arg(classes.toText());
4874 StatsMgr::instance().addValue("v4-allocation-fail-classes",
4875 static_cast<int64_t>(1));
4876 StatsMgr::instance().addValue(
4877 StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4878 "v4-allocation-fail-classes"),
4879 static_cast<int64_t>(1));
4880 }
4881
4882 return (new_lease);
4883}
4884
4885bool
4886AllocEngine::updateLease4Information(const Lease4Ptr& lease,
4887 AllocEngine::ClientContext4& ctx) const {
4888 bool changed = false;
4889 if (lease->subnet_id_ != ctx.subnet_->getID()) {
4890 changed = true;
4891 lease->subnet_id_ = ctx.subnet_->getID();
4892 }
4893 if ((!ctx.hwaddr_ && lease->hwaddr_) ||
4894 (ctx.hwaddr_ &&
4895 (!lease->hwaddr_ || (*ctx.hwaddr_ != *lease->hwaddr_)))) {
4896 changed = true;
4897 lease->hwaddr_ = ctx.hwaddr_;
4898 }
4899 if (ctx.subnet_->getMatchClientId() && ctx.clientid_) {
4900 if (!lease->client_id_ || (*ctx.clientid_ != *lease->client_id_)) {
4901 changed = true;
4902 lease->client_id_ = ctx.clientid_;
4903 }
4904 } else if (lease->client_id_) {
4905 changed = true;
4906 lease->client_id_ = ClientIdPtr();
4907 }
4908 lease->cltt_ = time(NULL);
4909
4910 // Get the context appropriate valid lifetime.
4911 lease->valid_lft_ = (ctx.offer_lft_ ? ctx.offer_lft_ : getValidLft(ctx));
4912
4913 // Valid lifetime has changed.
4914 if (lease->valid_lft_ != lease->current_valid_lft_) {
4915 changed = true;
4916 }
4917
4918 if ((lease->fqdn_fwd_ != ctx.fwd_dns_update_) ||
4919 (lease->fqdn_rev_ != ctx.rev_dns_update_) ||
4920 (lease->hostname_ != ctx.hostname_)) {
4921 changed = true;
4922 lease->fqdn_fwd_ = ctx.fwd_dns_update_;
4923 lease->fqdn_rev_ = ctx.rev_dns_update_;
4924 lease->hostname_ = ctx.hostname_;
4925 }
4926
4927 // Add (update) the extended information on the lease.
4928 if (updateLease4ExtendedInfo(lease, ctx)) {
4929 changed = true;
4930 }
4931
4932 return (changed);
4933}
4934
4935bool
4937 const AllocEngine::ClientContext4& ctx) const {
4938 bool changed = false;
4939
4940 // If storage is not enabled then punt.
4941 if (!ctx.subnet_->getStoreExtendedInfo()) {
4942 return (changed);
4943 }
4944
4945 // Look for relay agent information option (option 82)
4946 OptionPtr rai = ctx.query_->getOption(DHO_DHCP_AGENT_OPTIONS);
4947 if (!rai) {
4948 // Pkt4 doesn't have it, so nothing to store (or update).
4949 return (changed);
4950 }
4951
4952 // Create a StringElement with the hex string for relay-agent-info.
4953 ElementPtr relay_agent(new StringElement(rai->toHexString()));
4954
4955 // Now we wrap the agent info in a map. This allows for future expansion.
4956 ElementPtr extended_info = Element::createMap();
4957 extended_info->set("sub-options", relay_agent);
4958
4959 OptionPtr remote_id = rai->getOption(RAI_OPTION_REMOTE_ID);
4960 if (remote_id) {
4961 std::vector<uint8_t> bytes = remote_id->toBinary();
4962 lease->remote_id_ = bytes;
4963 if (bytes.size() > 0) {
4964 extended_info->set("remote-id",
4966 }
4967 }
4968
4969 OptionPtr relay_id = rai->getOption(RAI_OPTION_RELAY_ID);
4970 if (relay_id) {
4971 std::vector<uint8_t> bytes = relay_id->toBinary(false);
4972 lease->relay_id_ = bytes;
4973 if (bytes.size() > 0) {
4974 extended_info->set("relay-id",
4976 }
4977 }
4978
4979 // Get a mutable copy of the lease's current user context.
4980 ConstElementPtr user_context = lease->getContext();
4981 ElementPtr mutable_user_context;
4982 if (user_context && (user_context->getType() == Element::map)) {
4983 mutable_user_context = copy(user_context, 0);
4984 } else {
4985 mutable_user_context = Element::createMap();
4986 }
4987
4988 // Get a mutable copy of the ISC entry.
4989 ConstElementPtr isc = mutable_user_context->get("ISC");
4990 ElementPtr mutable_isc;
4991 if (isc && (isc->getType() == Element::map)) {
4992 mutable_isc = copy(isc, 0);
4993 } else {
4994 mutable_isc = Element::createMap();
4995 }
4996
4997 // Add/replace the extended info entry.
4998 ConstElementPtr old_extended_info = mutable_isc->get("relay-agent-info");
4999 if (!old_extended_info || (*old_extended_info != *extended_info)) {
5000 changed = true;
5001 mutable_isc->set("relay-agent-info", extended_info);
5002 mutable_user_context->set("ISC", mutable_isc);
5003 }
5004
5005 // Update the lease's user_context.
5006 lease->setContext(mutable_user_context);
5007
5008 return (changed);
5009}
5010
5011void
5013 const AllocEngine::ClientContext6& ctx) const {
5014 // The extended info action is a transient value but be safe so reset it.
5015 lease->extended_info_action_ = Lease6::ACTION_IGNORE;
5016
5017 // If storage is not enabled then punt.
5018 if (!ctx.subnet_->getStoreExtendedInfo()) {
5019 return;
5020 }
5021
5022 // If we do not have relay information, then punt.
5023 if (ctx.query_->relay_info_.empty()) {
5024 return;
5025 }
5026
5027 // We need to convert the vector of RelayInfo instances in
5028 // into an Element hierarchy like this:
5029 // "relay-info": [
5030 // {
5031 // "hop": 123,
5032 // "link": "2001:db8::1",
5033 // "peer": "2001:db8::2",
5034 // "options": "0x..."
5035 // },..]
5036 //
5037 ElementPtr extended_info = Element::createList();
5038 for (auto relay : ctx.query_->relay_info_) {
5039 ElementPtr relay_elem = Element::createMap();
5040 relay_elem->set("hop", ElementPtr(new IntElement(relay.hop_count_)));
5041 relay_elem->set("link", ElementPtr(new StringElement(relay.linkaddr_.toText())));
5042 relay_elem->set("peer", ElementPtr(new StringElement(relay.peeraddr_.toText())));
5043
5044 // If there are relay options, we'll pack them into a buffer and then
5045 // convert that into a hex string. If there are no options, we omit
5046 // then entry.
5047 if (!relay.options_.empty()) {
5048 OutputBuffer buf(128);
5049 LibDHCP::packOptions6(buf, relay.options_);
5050
5051 if (buf.getLength() > 0) {
5052 const uint8_t* cp = static_cast<const uint8_t*>(buf.getData());
5053 std::vector<uint8_t> bytes;
5054 std::stringstream ss;
5055
5056 bytes.assign(cp, cp + buf.getLength());
5057 ss << "0x" << encode::encodeHex(bytes);
5058 relay_elem->set("options", ElementPtr(new StringElement(ss.str())));
5059 }
5060
5061 auto remote_id_it = relay.options_.find(D6O_REMOTE_ID);
5062 if (remote_id_it != relay.options_.end()) {
5063 OptionPtr remote_id = remote_id_it->second;
5064 if (remote_id) {
5065 std::vector<uint8_t> bytes = remote_id->toBinary();
5066 if (bytes.size() > 0) {
5067 relay_elem->set("remote-id",
5069 }
5070 }
5071 }
5072
5073 auto relay_id_it = relay.options_.find(D6O_RELAY_ID);
5074 if (relay_id_it != relay.options_.end()) {
5075 OptionPtr relay_id = relay_id_it->second;
5076 if (relay_id) {
5077 std::vector<uint8_t> bytes = relay_id->toBinary(false);
5078 if (bytes.size() > 0) {
5079 relay_elem->set("relay-id",
5081 }
5082 }
5083 }
5084 }
5085
5086 extended_info->add(relay_elem);
5087 }
5088
5089 // Get a mutable copy of the lease's current user context.
5090 ConstElementPtr user_context = lease->getContext();
5091 ElementPtr mutable_user_context;
5092 if (user_context && (user_context->getType() == Element::map)) {
5093 mutable_user_context = copy(user_context, 0);
5094 } else {
5095 mutable_user_context = Element::createMap();
5096 }
5097
5098 // Get a mutable copy of the ISC entry.
5099 ConstElementPtr isc = mutable_user_context->get("ISC");
5100 ElementPtr mutable_isc;
5101 if (isc && (isc->getType() == Element::map)) {
5102 mutable_isc = copy(isc, 0);
5103 } else {
5104 mutable_isc = Element::createMap();
5105 }
5106
5107 // Add/replace the extended info entry.
5108 ConstElementPtr old_extended_info = mutable_isc->get("relay-info");
5109 if (!old_extended_info || (*old_extended_info != *extended_info)) {
5110 lease->extended_info_action_ = Lease6::ACTION_UPDATE;
5111 mutable_isc->set("relay-info", extended_info);
5112 mutable_user_context->set("ISC", mutable_isc);
5113 }
5114
5115 // Update the lease's user context.
5116 lease->setContext(mutable_user_context);
5117}
5118
5119void
5120AllocEngine::setLeaseReusable(const Lease4Ptr& lease,
5121 const ClientContext4& ctx) const {
5122 // Sanity.
5123 lease->reuseable_valid_lft_ = 0;
5124 const Subnet4Ptr& subnet = ctx.subnet_;
5125 if (!subnet) {
5126 return;
5127 }
5128 if (lease->state_ != Lease::STATE_DEFAULT) {
5129 return;
5130 }
5131
5132 // Always reuse infinite lifetime leases.
5133 if (lease->valid_lft_ == Lease::INFINITY_LFT) {
5134 lease->reuseable_valid_lft_ = Lease::INFINITY_LFT;
5135 return;
5136 }
5137
5138 // Refuse time not going forward.
5139 if (lease->cltt_ < lease->current_cltt_) {
5140 return;
5141 }
5142
5143 uint32_t age = lease->cltt_ - lease->current_cltt_;
5144 // Already expired.
5145 if (age >= lease->current_valid_lft_) {
5146 return;
5147 }
5148
5149 // Try cache max age.
5150 uint32_t max_age = 0;
5151 if (!subnet->getCacheMaxAge().unspecified()) {
5152 max_age = subnet->getCacheMaxAge().get();
5153 if ((max_age == 0) || (age > max_age)) {
5154 return;
5155 }
5156 }
5157
5158 // Try cache threshold.
5159 if (!subnet->getCacheThreshold().unspecified()) {
5160 double threshold = subnet->getCacheThreshold().get();
5161 if ((threshold <= 0.) || (threshold > 1.)) {
5162 return;
5163 }
5164 max_age = lease->valid_lft_ * threshold;
5165 if (age > max_age) {
5166 return;
5167 }
5168 }
5169
5170 // No cache.
5171 if (max_age == 0) {
5172 return;
5173 }
5174
5175 // Seems to be reusable.
5176 lease->reuseable_valid_lft_ = lease->current_valid_lft_ - age;
5177}
5178
5179void
5180AllocEngine::setLeaseReusable(const Lease6Ptr& lease,
5181 uint32_t current_preferred_lft,
5182 const ClientContext6& ctx) const {
5183 // Sanity.
5184 lease->reuseable_valid_lft_ = 0;
5185 lease->reuseable_preferred_lft_ = 0;
5186 const Subnet6Ptr& subnet = ctx.subnet_;
5187 if (!subnet) {
5188 return;
5189 }
5190 if (lease->state_ != Lease::STATE_DEFAULT) {
5191 return;
5192 }
5193
5194 // Refuse time not going forward.
5195 if (lease->cltt_ < lease->current_cltt_) {
5196 return;
5197 }
5198
5199 uint32_t age = lease->cltt_ - lease->current_cltt_;
5200 // Already expired.
5201 if (age >= lease->current_valid_lft_) {
5202 return;
5203 }
5204
5205 // Try cache max age.
5206 uint32_t max_age = 0;
5207 if (!subnet->getCacheMaxAge().unspecified()) {
5208 max_age = subnet->getCacheMaxAge().get();
5209 if ((max_age == 0) || (age > max_age)) {
5210 return;
5211 }
5212 }
5213
5214 // Try cache threshold.
5215 if (!subnet->getCacheThreshold().unspecified()) {
5216 double threshold = subnet->getCacheThreshold().get();
5217 if ((threshold <= 0.) || (threshold > 1.)) {
5218 return;
5219 }
5220 max_age = lease->valid_lft_ * threshold;
5221 if (age > max_age) {
5222 return;
5223 }
5224 }
5225
5226 // No cache.
5227 if (max_age == 0) {
5228 return;
5229 }
5230
5231 // Seems to be reusable.
5232 if ((current_preferred_lft == Lease::INFINITY_LFT) ||
5233 (current_preferred_lft == 0)) {
5234 // Keep these values.
5235 lease->reuseable_preferred_lft_ = current_preferred_lft;
5236 } else if (current_preferred_lft > age) {
5237 lease->reuseable_preferred_lft_ = current_preferred_lft - age;
5238 } else {
5239 // Can be a misconfiguration so stay safe...
5240 return;
5241 }
5242 if (lease->current_valid_lft_ == Lease::INFINITY_LFT) {
5243 lease->reuseable_valid_lft_ = Lease::INFINITY_LFT;
5244 } else {
5245 lease->reuseable_valid_lft_ = lease->current_valid_lft_ - age;
5246 }
5247}
5248
5249} // namespace dhcp
5250} // namespace isc
CtrlAgentHooks Hooks
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
This is a base class for exceptions thrown from the DNS library module.
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown if a function is called in a prohibited way.
static ElementPtr create(const Position &pos=ZERO_POSITION())
Definition: data.cc:249
static ElementPtr createMap(const Position &pos=ZERO_POSITION())
Creates an empty MapElement type ElementPtr.
Definition: data.cc:304
static ElementPtr createList(const Position &pos=ZERO_POSITION())
Creates an empty ListElement type ElementPtr.
Definition: data.cc:299
Notes: IntElement type is changed to int64_t.
Definition: data.h:615
Defines a single hint.
Definition: alloc_engine.h:83
static IPv6Resrv makeIPv6Resrv(const Lease6 &lease)
Creates an IPv6Resrv instance from a Lease6.
Definition: alloc_engine.h:788
void updateLease6ExtendedInfo(const Lease6Ptr &lease, const ClientContext6 &ctx) const
Stores additional client query parameters on a V6 lease.
void reclaimExpiredLeases6Internal(const size_t max_leases, const uint16_t timeout, const bool remove_lease, const uint16_t max_unwarned_cycles=0)
Body of reclaimExpiredLeases6.
bool updateLease4ExtendedInfo(const Lease4Ptr &lease, const ClientContext4 &ctx) const
Stores additional client query parameters on a V4 lease.
static uint32_t getOfferLft(const ClientContext4 &ctx)
Returns the offer lifetime based on the v4 context.
static std::string labelNetworkOrSubnet(SubnetPtr subnet)
Generates a label for subnet or shared-network from subnet.
static ConstHostPtr findGlobalReservation(ClientContext6 &ctx)
Attempts to find the host reservation for the client.
AllocEngine(isc::util::uint128_t const &attempts)
Constructor.
Definition: alloc_engine.cc:92
std::pair< Host::IdentifierType, std::vector< uint8_t > > IdentifierPair
A tuple holding host identifier type and value.
Definition: alloc_engine.h:191
void clearReclaimedExtendedInfo(const Lease4Ptr &lease) const
Clear extended info from a reclaimed V4 lease.
isc::util::ReadWriteMutex rw_mutex_
The read-write mutex.
static void getLifetimes6(ClientContext6 &ctx, uint32_t &preferred, uint32_t &valid)
Determines the preferred and valid v6 lease lifetimes.
static void findReservation(ClientContext6 &ctx)
void reclaimExpiredLeases4Internal(const size_t max_leases, const uint16_t timeout, const bool remove_lease, const uint16_t max_unwarned_cycles=0)
Body of reclaimExpiredLeases4.
void deleteExpiredReclaimedLeases4(const uint32_t secs)
Deletes reclaimed leases expired more than specified amount of time ago.
static uint32_t getValidLft(const ClientContext4 &ctx)
Returns the valid lifetime based on the v4 context.
void reclaimExpiredLeases6(const size_t max_leases, const uint16_t timeout, const bool remove_lease, const uint16_t max_unwarned_cycles=0)
Reclaims expired IPv6 leases.
void reclaimExpiredLeases4(const size_t max_leases, const uint16_t timeout, const bool remove_lease, const uint16_t max_unwarned_cycles=0)
Reclaims expired IPv4 leases.
Lease4Ptr allocateLease4(ClientContext4 &ctx)
Returns IPv4 lease.
void deleteExpiredReclaimedLeases6(const uint32_t secs)
Deletes reclaimed leases expired more than specified amount of time ago.
Lease6Collection allocateLeases6(ClientContext6 &ctx)
Allocates IPv6 leases for a given IA container.
Lease6Collection renewLeases6(ClientContext6 &ctx)
Renews existing DHCPv6 leases for a given IA.
PrefixLenMatchType
Type of preferred PD-pool prefix length selection criteria.
Definition: allocator.h:61
static bool isValidPrefixPool(Allocator::PrefixLenMatchType prefix_length_match, PoolPtr pool, uint8_t hint_prefix_length)
Check if the pool matches the selection criteria relative to the provided hint prefix length.
Definition: allocator.cc:39
D2ClientMgr & getD2ClientMgr()
Fetches the DHCP-DDNS manager.
Definition: cfgmgr.cc:66
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition: cfgmgr.cc:25
SrvConfigPtr getCurrentCfg()
Returns a pointer to the current configuration.
Definition: cfgmgr.cc:161
Container for storing client class names.
Definition: classify.h:108
ClientClassContainer::const_iterator const_iterator
Type of iterators.
Definition: classify.h:112
bool empty() const
Check if classes is empty.
Definition: classify.h:138
const_iterator cbegin() const
Iterators to the first element.
Definition: classify.h:152
const_iterator cend() const
Iterators to the past the end element.
Definition: classify.h:165
Convenience container for conveying DDNS behavioral parameters It is intended to be created per Packe...
Definition: srv_config.h:48
ConstHostCollection getAll4(const SubnetID &subnet_id, const HostMgrOperationTarget target) const
Return all hosts in a DHCPv4 subnet.
Definition: host_mgr.cc:153
ConstHostCollection getAll(const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len, const HostMgrOperationTarget target) const
Return all hosts connected to any subnet for which reservations have been made using a specified iden...
Definition: host_mgr.cc:125
bool getDisableSingleQuery() const
Returns the disable single query flag.
Definition: host_mgr.h:796
static HostMgr & instance()
Returns a sole instance of the HostMgr.
Definition: host_mgr.cc:116
ConstHostPtr get4(const SubnetID &subnet_id, const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len, const HostMgrOperationTarget target) const
Returns a host connected to the IPv4 subnet.
Definition: host_mgr.cc:467
ConstHostPtr get6(const SubnetID &subnet_id, const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len, const HostMgrOperationTarget target) const
Returns a host connected to the IPv6 subnet.
Definition: host_mgr.cc:652
@ IDENT_HWADDR
Definition: host.h:308
IPv6 reservation for a host.
Definition: host.h:161
Type
Type of the reservation.
Definition: host.h:167
static TrackingLeaseMgr & instance()
Return current lease manager.
Abstract Lease Manager.
Definition: lease_mgr.h:248
virtual Lease6Collection getLeases6(Lease::Type type, const DUID &duid, uint32_t iaid) const =0
Returns existing IPv6 leases for a given DUID+IA combination.
virtual void getExpiredLeases6(Lease6Collection &expired_leases, const size_t max_leases) const =0
Returns a collection of expired DHCPv6 leases.
virtual uint64_t deleteExpiredReclaimedLeases6(const uint32_t secs)=0
Deletes all expired and reclaimed DHCPv6 leases.
virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress &addr) const =0
Returns an IPv4 lease for specified IPv4 address.
virtual uint64_t deleteExpiredReclaimedLeases4(const uint32_t secs)=0
Deletes all expired and reclaimed DHCPv4 leases.
virtual bool addLease(const Lease4Ptr &lease)=0
Adds an IPv4 lease.
virtual bool deleteLease(const Lease4Ptr &lease)=0
Deletes an IPv4 lease.
virtual void getExpiredLeases4(Lease4Collection &expired_leases, const size_t max_leases) const =0
Returns a collection of expired DHCPv4 leases.
virtual void updateLease4(const Lease4Ptr &lease4)=0
Updates IPv4 lease.
virtual Lease6Ptr getLease6(Lease::Type type, const isc::asiolink::IOAddress &addr) const =0
Returns existing IPv6 lease for a given IPv6 address.
virtual void updateLease6(const Lease6Ptr &lease6)=0
Updates IPv6 lease.
static void packOptions6(isc::util::OutputBuffer &buf, const isc::dhcp::OptionCollection &options)
Stores DHCPv6 options in a buffer.
Definition: libdhcp++.cc:1236
static std::string makeLabel(const HWAddrPtr &hwaddr, const ClientIdPtr &client_id, const uint32_t transid)
Returns text representation of the given packet identifiers.
Definition: pkt4.cc:405
static std::string makeLabel(const DuidPtr duid, const uint32_t transid, const HWAddrPtr &hwaddr)
Returns text representation of the given packet identifiers.
Definition: pkt6.cc:694
Resource race avoidance RAII handler for DHCPv4.
bool tryLock4(const asiolink::IOAddress &addr)
Tries to acquires a resource.
Resource race avoidance RAII handler.
bool tryLock(Lease::Type type, const asiolink::IOAddress &addr)
Tries to acquires a resource.
RAII object enabling copying options retrieved from the packet.
Definition: pkt.h:46
static bool subnetsIncludeMatchClientId(const Subnet4Ptr &first_subnet, const ClientClasses &client_classes)
Checks if the shared network includes a subnet with the match client ID flag set to true.
CalloutNextStep
Specifies allowed next steps.
Wrapper class around callout handle which automatically resets handle's state.
Statistics Manager class.
T get() const
Retrieves the encapsulated value.
Definition: optional.h:114
void unspecified(bool unspecified)
Modifies the flag that indicates whether the value is specified or unspecified.
Definition: optional.h:136
The OutputBuffer class is a buffer abstraction for manipulating mutable data.
Definition: buffer.h:294
size_t getLength() const
Return the length of data written in the buffer.
Definition: buffer.h:403
const void * getData() const
Return a pointer to the head of the data stored in the buffer.
Definition: buffer.h:401
Utility class to measure code execution times.
Definition: stopwatch.h:35
long getTotalMilliseconds() const
Retrieves the total measured duration in milliseconds.
Definition: stopwatch.cc:60
void stop()
Stops the stopwatch.
Definition: stopwatch.cc:35
std::string logFormatTotalDuration() const
Returns the total measured duration in the format directly usable in the log messages.
Definition: stopwatch.cc:80
T get(T hint) const
Returns value with a hint.
Definition: triplet.h:99
Write mutex RAII handler.
@ D6O_CLIENT_FQDN
Definition: dhcp6.h:59
@ D6O_REMOTE_ID
Definition: dhcp6.h:57
@ D6O_RELAY_ID
Definition: dhcp6.h:73
@ DHCPV6_RENEW
Definition: dhcp6.h:202
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
boost::shared_ptr< OptionUint32 > OptionUint32Ptr
Definition: option_int.h:35
void addValue(const std::string &name, const int64_t value)
Records incremental integer observation.
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition: macros.h:32
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition: macros.h:20
#define LOG_WARN(LOGGER, MESSAGE)
Macro to conveniently test warn output and log it.
Definition: macros.h:26
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition: macros.h:14
ElementPtr copy(ConstElementPtr from, int level)
Copy the data up to a nesting level.
Definition: data.cc:1414
boost::shared_ptr< const Element > ConstElementPtr
Definition: data.h:29
boost::shared_ptr< Element > ElementPtr
Definition: data.h:28
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_NO_LEASES_HR
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_INVALID
const isc::log::MessageID ALLOC_ENGINE_V4_LEASE_RECLAMATION_FAILED
isc::log::Logger dhcpsrv_logger("dhcpsrv")
DHCP server library Logger.
Definition: dhcpsrv_log.h:56
const isc::log::MessageID ALLOC_ENGINE_V4_ALLOC_FAIL_NO_POOLS
const isc::log::MessageID ALLOC_ENGINE_IGNORING_UNSUITABLE_GLOBAL_ADDRESS6
const isc::log::MessageID DHCPSRV_HOOK_LEASE4_RECOVER_SKIP
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_EXTEND_LEASE
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_IN_USE
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_HR_LEASE_EXISTS
const isc::log::MessageID ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE_FAILED
const isc::log::MessageID ALLOC_ENGINE_V6_RENEW_HR
const isc::log::MessageID ALLOC_ENGINE_V6_EXTEND_LEASE_DATA
const isc::log::MessageID ALLOC_ENGINE_V4_REUSE_EXPIRED_LEASE_DATA
const isc::log::MessageID ALLOC_ENGINE_V6_EXTEND_LEASE
boost::shared_ptr< Subnet > SubnetPtr
A generic pointer to either Subnet4 or Subnet6 object.
Definition: subnet.h:489
const isc::log::MessageID ALLOC_ENGINE_V6_REVOKED_SHARED_PREFIX_LEASE
boost::shared_ptr< Subnet4 > Subnet4Ptr
A pointer to a Subnet4 object.
Definition: subnet.h:498
const isc::log::MessageID ALLOC_ENGINE_V6_REUSE_EXPIRED_LEASE_DATA
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_NO_V6_HR
const isc::log::MessageID ALLOC_ENGINE_V6_REVOKED_SHARED_ADDR_LEASE
const isc::log::MessageID ALLOC_ENGINE_V4_ALLOC_ERROR
const isc::log::MessageID ALLOC_ENGINE_V6_HINT_RESERVED
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_OUT_OF_POOL
const isc::log::MessageID ALLOC_ENGINE_V6_LEASES_RECLAMATION_SLOW
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_ADDRESS_RESERVED
isc::log::Logger alloc_engine_logger("alloc-engine")
Logger for the AllocEngine.
void queueNCR(const NameChangeType &chg_type, const Lease4Ptr &lease)
Creates name change request from the DHCPv4 lease.
const isc::log::MessageID ALLOC_ENGINE_V4_OFFER_REQUESTED_LEASE
const isc::log::MessageID ALLOC_ENGINE_LEASE_RECLAIMED
@ DHO_DHCP_AGENT_OPTIONS
Definition: dhcp4.h:151
@ DHO_DHCP_LEASE_TIME
Definition: dhcp4.h:120
const int ALLOC_ENGINE_DBG_TRACE
Logging levels for the AllocEngine.