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