Kea 2.7.5
cb_ctl_dhcp4.cc
Go to the documentation of this file.
1// Copyright (C) 2019-2024 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>
9#include <dhcpsrv/cfgmgr.h>
11#include <dhcpsrv/dhcpsrv_log.h>
12#include <dhcpsrv/host_mgr.h>
15#include <hooks/hooks_manager.h>
16#include <boost/foreach.hpp>
17
18using namespace isc::db;
19using namespace isc::data;
20using namespace isc::process;
21using namespace isc::hooks;
22
23namespace {
24
26struct CbCtlHooks {
27 int hook_index_cb4_updated_;
28
30 CbCtlHooks() {
31 hook_index_cb4_updated_ = HooksManager::registerHook("cb4_updated");
32 }
33};
34
35// Declare a Hooks object. As this is outside any function or method, it
36// will be instantiated (and the constructor run) when the module is loaded.
37// As a result, the hook indexes will be defined before any method in this
38// module is called.
39CbCtlHooks hooks_;
40
41} // anonymous namespace
42
43namespace isc {
44namespace dhcp {
45
46void
48 const ServerSelector& server_selector,
49 const boost::posix_time::ptime& lb_modification_time,
50 const AuditEntryCollection& audit_entries) {
51
52 auto globals_fetched = false;
53 auto reconfig = audit_entries.empty();
54 auto cb_update = !reconfig;
55 auto current_cfg = CfgMgr::instance().getCurrentCfg();
56 auto staging_cfg = CfgMgr::instance().getStagingCfg();
57
58 // Let's first delete all the configuration elements for which DELETE audit
59 // entries are found. Although, this may break chronology of the audit in
60 // some cases it should not affect the end result of the data fetch. If the
61 // object was created and then subsequently deleted, we will first try to
62 // delete this object from the local configuration (which will fail because
63 // the object does not exist) and then we will try to fetch it from the
64 // database which will return no result.
65 if (cb_update) {
66
67 auto external_cfg = CfgMgr::instance().createExternalCfg();
68
69 // Get audit entries for deleted global parameters.
70 auto const& index = audit_entries.get<AuditEntryObjectTypeTag>();
71 auto range = index.equal_range(boost::make_tuple("dhcp4_global_parameter",
72 AuditEntry::ModificationType::DELETE));
73 if (range.first != range.second) {
74 // Some globals have been deleted. Since we currently don't track database
75 // identifiers of the global parameters we have to fetch all global
76 // parameters for this server. Next, we simply replace existing
77 // global parameters with the new parameters. This is slightly
78 // inefficient but only slightly. Note that this is a single
79 // database query and the number of global parameters is small.
81 globals = getMgr().getPool()->getAllGlobalParameters4(backend_selector, server_selector);
82 translateAndAddGlobalsToConfig(external_cfg, globals);
83
84 // Add defaults.
85 external_cfg->applyDefaultsConfiguredGlobals(SimpleParser4::GLOBAL4_DEFAULTS);
86
87 // Sanity check it.
88 external_cfg->sanityChecksLifetime("valid-lifetime");
89
90 // Now that we successfully fetched the new global parameters, let's
91 // remove existing ones and merge them into the current configuration.
92 current_cfg->clearConfiguredGlobals();
93 CfgMgr::instance().mergeIntoCurrentCfg(external_cfg->getSequence());
94 globals_fetched = true;
95 }
96
97 try {
98 // Get audit entries for deleted option definitions and delete each
99 // option definition from the current configuration for which the
100 // audit entry is found.
101 range = index.equal_range(boost::make_tuple("dhcp4_option_def",
102 AuditEntry::ModificationType::DELETE));
103 BOOST_FOREACH(auto const& entry, range) {
104 current_cfg->getCfgOptionDef()->del(entry->getObjectId());
105 }
106
107 // Repeat the same for other configuration elements.
108
109 range = index.equal_range(boost::make_tuple("dhcp4_options",
110 AuditEntry::ModificationType::DELETE));
111 BOOST_FOREACH(auto const& entry, range) {
112 current_cfg->getCfgOption()->del(entry->getObjectId());
113 }
114
115 range = index.equal_range(boost::make_tuple("dhcp4_client_class",
116 AuditEntry::ModificationType::DELETE));
117 BOOST_FOREACH(auto const& entry, range) {
118 current_cfg->getClientClassDictionary()->removeClass(entry->getObjectId());
119 }
120
121 range = index.equal_range(boost::make_tuple("dhcp4_shared_network",
122 AuditEntry::ModificationType::DELETE));
123 BOOST_FOREACH(auto const& entry, range) {
124 current_cfg->getCfgSharedNetworks4()->del(entry->getObjectId());
125 }
126
127 range = index.equal_range(boost::make_tuple("dhcp4_subnet",
128 AuditEntry::ModificationType::DELETE));
129 BOOST_FOREACH(auto const& entry, range) {
130 // If the deleted subnet belongs to a shared network and the
131 // shared network is not being removed, we need to detach the
132 // subnet from the shared network.
133 auto subnet = current_cfg->getCfgSubnets4()->getBySubnetId(entry->getObjectId());
134 if (subnet) {
135 // Check if the subnet belongs to a shared network.
136 SharedNetwork4Ptr network;
137 subnet->getSharedNetwork(network);
138 if (network) {
139 // Detach the subnet from the shared network.
140 network->del(subnet->getID());
141 }
142 // Actually delete the subnet from the configuration.
143 current_cfg->getCfgSubnets4()->del(entry->getObjectId());
144 }
145 }
146
147 } catch (...) {
148 // Ignore errors thrown when attempting to delete a non-existing
149 // configuration entry. There is no guarantee that the deleted
150 // entry is actually there as we're not processing the audit
151 // chronologically.
152 }
153 }
154
155 // Create the external config into which we'll fetch backend config data.
156 auto external_cfg = CfgMgr::instance().createExternalCfg();
157
158 // First let's fetch the globals and add them to external config.
159 AuditEntryCollection updated_entries;
160 if (!globals_fetched) {
161 if (cb_update) {
162 updated_entries = fetchConfigElement(audit_entries, "dhcp4_global_parameter");
163 }
164 if (reconfig || !updated_entries.empty()) {
166 globals = getMgr().getPool()->getModifiedGlobalParameters4(backend_selector, server_selector,
167 lb_modification_time);
168 translateAndAddGlobalsToConfig(external_cfg, globals);
169 globals_fetched = true;
170 }
171 }
172
173 // Now we fetch the option definitions and add them.
174 if (cb_update) {
175 updated_entries = fetchConfigElement(audit_entries, "dhcp4_option_def");
176 }
177 if (reconfig || !updated_entries.empty()) {
178 OptionDefContainer option_defs =
179 getMgr().getPool()->getModifiedOptionDefs4(backend_selector, server_selector,
180 lb_modification_time);
181 for (auto const& option_def : option_defs) {
182 if (!audit_entries.empty() && !hasObjectId(updated_entries, option_def->getId())) {
183 continue;
184 }
185 external_cfg->getCfgOptionDef()->add(option_def);
186 }
187 }
188
189 // Next fetch the options. They are returned as a container of OptionDescriptors.
190 if (cb_update) {
191 updated_entries = fetchConfigElement(audit_entries, "dhcp4_options");
192 }
193 if (reconfig || !updated_entries.empty()) {
194 OptionContainer options = getMgr().getPool()->getModifiedOptions4(backend_selector,
195 server_selector,
196 lb_modification_time);
197 for (auto const& option : options) {
198 if (!audit_entries.empty() && !hasObjectId(updated_entries, option.getId())) {
199 continue;
200 }
201 external_cfg->getCfgOption()->add(option, option.space_name_);
202 }
203 }
204
205 // Fetch client classes. They are returned in a ClientClassDictionary.
206 if (cb_update) {
207 updated_entries = fetchConfigElement(audit_entries, "dhcp4_client_class");
208 }
209 if (reconfig || !updated_entries.empty()) {
210 ClientClassDictionary client_classes = getMgr().getPool()->getAllClientClasses4(backend_selector,
211 server_selector);
212 // Match expressions are not initialized for classes returned from the config backend.
213 // We have to ensure to initialize them before they can be used by the server.
214 client_classes.initMatchExpr(AF_INET);
215
216 // Class options also need to be created when returned from the config backend.
217 client_classes.createOptions(external_cfg->getCfgOptionDef());
218 client_classes.encapsulateOptions();
219
220 external_cfg->setClientClassDictionary(boost::make_shared<ClientClassDictionary>(client_classes));
221 }
222
223 // Allocator selection at the global level can affect subnets and shared networks
224 // for which the allocator hasn't been specified explicitly. Let's see if the
225 // allocator has been specified at the global level.
226 std::string global_allocator;
227 auto allocator = external_cfg->getConfiguredGlobal(CfgGlobals::ALLOCATOR);
228 if (allocator && (allocator->getType() == Element::string)) {
229 global_allocator = allocator->stringValue();
230 }
231
232 // If we're fetching the changes from the config backend we also want
233 // to see if the global allocator has changed. Let's get the currently
234 // used allocator too.
235 auto allocator_changed = false;
236 // We're only affected by the allocator change if this is the update from
237 // the configuration backend.
238 if (cb_update) {
239 allocator = CfgMgr::instance().getCurrentCfg()->getConfiguredGlobal(CfgGlobals::ALLOCATOR);
240 if (allocator && (allocator->getType() == Element::string)) {
241 allocator_changed = (global_allocator != allocator->stringValue());
242 }
243 }
244
245 // Now fetch the shared networks.
246 if (cb_update) {
247 updated_entries = fetchConfigElement(audit_entries, "dhcp4_shared_network");
248 }
250 if (allocator_changed || reconfig) {
251 // A change of the allocator or the server reconfiguration can affect all
252 // shared networks. Get all shared networks.
253 networks = getMgr().getPool()->getAllSharedNetworks4(backend_selector, server_selector);
254
255 } else if (!updated_entries.empty()) {
256 // An update from the config backend when the global allocator hasn't changed
257 // means that we only need to handle the modified subnets.
258 networks = getMgr().getPool()->getModifiedSharedNetworks4(backend_selector, server_selector,
259 lb_modification_time);
260 }
261 // Iterate over all shared networks that may require reconfiguration.
262 for (auto const& network : networks) {
263 if (!allocator_changed && cb_update && !hasObjectId(updated_entries, network->getId())) {
264 continue;
265 }
266 // In order to take advantage of the dynamic inheritance of global
267 // parameters to a shared network we need to set a callback function
268 // for each network to allow for fetching global parameters.
269 network->setFetchGlobalsFn([] () -> ConstCfgGlobalsPtr {
270 return (CfgMgr::instance().getCurrentCfg()->getConfiguredGlobals());
271 });
272 network->setDefaultAllocatorType(global_allocator);
273 external_cfg->getCfgSharedNetworks4()->add(network);
274 }
275
276 // Next, fetch the subnets.
277 if (cb_update) {
278 updated_entries = fetchConfigElement(audit_entries, "dhcp4_subnet");
279 }
280 Subnet4Collection subnets;
281 if (allocator_changed || reconfig) {
282 // A change of the allocator or the server reconfiguration can affect all
283 // subnets. Get all subnets.
284 subnets = getMgr().getPool()->getAllSubnets4(backend_selector, server_selector);
285
286 } else if (!updated_entries.empty()) {
287 // An update from the config backend when the global allocator hasn't changed
288 // means that we only need to handle the modified subnets.
289 subnets = getMgr().getPool()->getModifiedSubnets4(backend_selector,
290 server_selector,
291 lb_modification_time);
292 }
293 // Iterate over all subnets that may require reconfiguration.
294 for (auto const& subnet : subnets) {
295 if (!allocator_changed && cb_update && !hasObjectId(updated_entries, subnet->getID())) {
296 continue;
297 }
298 // In order to take advantage of the dynamic inheritance of global
299 // parameters to a subnet we need to set a callback function for each
300 // subnet to allow for fetching global parameters.
301 subnet->setFetchGlobalsFn([] () -> ConstCfgGlobalsPtr {
302 return (CfgMgr::instance().getCurrentCfg()->getConfiguredGlobals());
303 });
304 subnet->setDefaultAllocatorType(global_allocator);
305 external_cfg->getCfgSubnets4()->add(subnet);
306 }
307
308 if (reconfig) {
309 // If we're configuring the server after startup, we do not apply the
310 // ip-reservations-unique setting here. It will be applied when the
311 // configuration is committed.
312 external_cfg->sanityChecksLifetime(*staging_cfg, "valid-lifetime");
313 CfgMgr::instance().mergeIntoStagingCfg(external_cfg->getSequence());
314
315 } else {
316 if (globals_fetched) {
317 // ip-reservations-unique parameter requires special handling because
318 // setting it to false may be unsupported by some host backends.
319 bool ip_unique = true;
320 auto ip_unique_param = external_cfg->getConfiguredGlobal("ip-reservations-unique");
321 if (ip_unique_param && (ip_unique_param->getType() == Element::boolean)) {
322 ip_unique = ip_unique_param->boolValue();
323 }
324 // First try to use the new setting to configure the HostMgr because it
325 // may fail if the backend does not support it.
326 if (!HostMgr::instance().setIPReservationsUnique(ip_unique)) {
327 // The new setting is unsupported by the backend, so do not apply this
328 // setting at all.
330 external_cfg->addConfiguredGlobal("ip-reservations-unique", Element::create(true));
331 }
332 }
333 external_cfg->sanityChecksLifetime(*current_cfg, "valid-lifetime");
334 CfgMgr::instance().mergeIntoCurrentCfg(external_cfg->getSequence());
335 CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->initAllocatorsAfterConfigure();
336 }
337
339
340 if (cb_update &&
341 HooksManager::calloutsPresent(hooks_.hook_index_cb4_updated_)) {
343
344 // Use the RAII wrapper to make sure that the callout handle state is
345 // reset when this object goes out of scope. All hook points must do
346 // it to prevent possible circular dependency between the callout
347 // handle and its arguments.
348 ScopedCalloutHandleState callout_handle_state(callout_handle);
349
350 // Pass a shared pointer to audit entries.
351 AuditEntryCollectionPtr ptr(new AuditEntryCollection(audit_entries));
352 callout_handle->setArgument("audit_entries", ptr);
353
354 // Call the callouts
355 HooksManager::callCallouts(hooks_.hook_index_cb4_updated_, *callout_handle);
356
357 // Ignore the result.
358 }
359}
360
361} // end of namespace isc::dhcp
362} // end of namespace isc
static ElementPtr create(const Position &pos=ZERO_POSITION())
Definition data.cc:249
Config Backend selector.
Server selector for associating objects in a database with specific servers.
void translateAndAddGlobalsToConfig(SrvConfigPtr external_cfg, data::StampedValueCollection &cb_globals) const
It translates the top level map parameters from flat naming format (e.g.
Definition cb_ctl_dhcp.h:72
virtual void databaseConfigApply(const db::BackendSelector &backend_selector, const db::ServerSelector &server_selector, const boost::posix_time::ptime &lb_modification_time, const db::AuditEntryCollection &audit_entries)
DHCPv4 server specific method to fetch and apply back end configuration into the local configuration.
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition cfgmgr.cc:28
Maintains a list of ClientClassDef's.
static HostMgr & instance()
Returns a sole instance of the HostMgr.
Definition host_mgr.cc:114
static const isc::data::SimpleDefaults GLOBAL4_DEFAULTS
This table defines default global values for DHCPv4.
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.
db::AuditEntryCollection fetchConfigElement(const db::AuditEntryCollection &audit_entries, const std::string &object_type) const
Returns audit entries for new or updated configuration elements of specific type to be fetched from t...
ConfigBackendMgrType & getMgr() const
Returns the instance of the Config Backend Manager used by this object.
Defines classes for storing client class definitions.
#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
boost::multi_index_container< StampedValuePtr, boost::multi_index::indexed_by< boost::multi_index::hashed_non_unique< boost::multi_index::tag< StampedValueNameIndexTag >, boost::multi_index::const_mem_fun< StampedValue, std::string, &StampedValue::getName > >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< StampedValueModificationTimeIndexTag >, boost::multi_index::const_mem_fun< BaseStampedElement, boost::posix_time::ptime, &BaseStampedElement::getModificationTime > > > > StampedValueCollection
Multi index container for StampedValue.
boost::multi_index_container< AuditEntryPtr, boost::multi_index::indexed_by< boost::multi_index::ordered_non_unique< boost::multi_index::tag< AuditEntryObjectTypeTag >, boost::multi_index::composite_key< AuditEntry, boost::multi_index::const_mem_fun< AuditEntry, std::string, &AuditEntry::getObjectType >, boost::multi_index::const_mem_fun< AuditEntry, AuditEntry::ModificationType, &AuditEntry::getModificationType > > >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< AuditEntryModificationTimeIdTag >, boost::multi_index::composite_key< AuditEntry, boost::multi_index::const_mem_fun< AuditEntry, boost::posix_time::ptime, &AuditEntry::getModificationTime >, boost::multi_index::const_mem_fun< AuditEntry, uint64_t, &AuditEntry::getRevisionId > > >, boost::multi_index::hashed_non_unique< boost::multi_index::tag< AuditEntryObjectIdTag >, boost::multi_index::const_mem_fun< AuditEntry, uint64_t, &AuditEntry::getObjectId > > > > AuditEntryCollection
Multi index container holding AuditEntry instances.
boost::shared_ptr< AuditEntryCollection > AuditEntryCollectionPtr
isc::log::Logger dhcpsrv_logger("dhcpsrv")
DHCP server library Logger.
Definition dhcpsrv_log.h:56
boost::shared_ptr< const CfgGlobals > ConstCfgGlobalsPtr
Const shared pointer to a CfgGlobals instance.
const isc::log::MessageID DHCPSRV_CFGMGR_CONFIG4_MERGED
const isc::log::MessageID DHCPSRV_CFGMGR_IPV4_RESERVATIONS_NON_UNIQUE_IGNORED
boost::multi_index_container< Subnet4Ptr, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< boost::multi_index::tag< SubnetSubnetIdIndexTag >, boost::multi_index::const_mem_fun< Subnet, SubnetID, &Subnet::getID > >, boost::multi_index::ordered_unique< boost::multi_index::tag< SubnetPrefixIndexTag >, boost::multi_index::const_mem_fun< Subnet, std::string, &Subnet::toText > >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< SubnetServerIdIndexTag >, boost::multi_index::const_mem_fun< Network4, asiolink::IOAddress, &Network4::getServerId > >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< SubnetModificationTimeIndexTag >, boost::multi_index::const_mem_fun< data::BaseStampedElement, boost::posix_time::ptime, &data::BaseStampedElement::getModificationTime > > > > Subnet4Collection
A collection of Subnet4 objects.
Definition subnet.h:866
boost::multi_index_container< SharedNetwork4Ptr, boost::multi_index::indexed_by< boost::multi_index::random_access< boost::multi_index::tag< SharedNetworkRandomAccessIndexTag > >, boost::multi_index::hashed_non_unique< boost::multi_index::tag< SharedNetworkIdIndexTag >, boost::multi_index::const_mem_fun< data::BaseStampedElement, uint64_t, &data::BaseStampedElement::getId > >, boost::multi_index::ordered_unique< boost::multi_index::tag< SharedNetworkNameIndexTag >, boost::multi_index::const_mem_fun< SharedNetwork4, std::string, &SharedNetwork4::getName > >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< SharedNetworkServerIdIndexTag >, boost::multi_index::const_mem_fun< Network4, asiolink::IOAddress, &Network4::getServerId > >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< SharedNetworkModificationTimeIndexTag >, boost::multi_index::const_mem_fun< data::BaseStampedElement, boost::posix_time::ptime, &data::BaseStampedElement::getModificationTime > > > > SharedNetwork4Collection
Multi index container holding shared networks.
boost::multi_index_container< OptionDescriptor, boost::multi_index::indexed_by< boost::multi_index::sequenced<>, boost::multi_index::hashed_non_unique< KeyFromKeyExtractor< boost::multi_index::const_mem_fun< Option, uint16_t, &Option::getType >, boost::multi_index::member< OptionDescriptor, OptionPtr, &OptionDescriptor::option_ > > >, boost::multi_index::hashed_non_unique< boost::multi_index::member< OptionDescriptor, bool, &OptionDescriptor::persistent_ > >, boost::multi_index::ordered_non_unique< boost::multi_index::const_mem_fun< data::BaseStampedElement, boost::posix_time::ptime, &data::BaseStampedElement::getModificationTime > >, boost::multi_index::hashed_non_unique< boost::multi_index::tag< OptionIdIndexTag >, boost::multi_index::const_mem_fun< data::BaseStampedElement, uint64_t, &data::BaseStampedElement::getId > >, boost::multi_index::hashed_non_unique< boost::multi_index::member< OptionDescriptor, bool, &OptionDescriptor::cancelled_ > > > > OptionContainer
Multi index container for DHCP option descriptors.
Definition cfg_option.h:320
boost::shared_ptr< SharedNetwork4 > SharedNetwork4Ptr
Pointer to SharedNetwork4 object.
boost::multi_index_container< OptionDefinitionPtr, boost::multi_index::indexed_by< boost::multi_index::sequenced<>, boost::multi_index::hashed_non_unique< boost::multi_index::const_mem_fun< OptionDefinition, uint16_t, &OptionDefinition::getCode > >, boost::multi_index::hashed_non_unique< boost::multi_index::const_mem_fun< OptionDefinition, std::string, &OptionDefinition::getName > >, boost::multi_index::ordered_non_unique< boost::multi_index::const_mem_fun< data::BaseStampedElement, boost::posix_time::ptime, &data::StampedElement::getModificationTime > >, boost::multi_index::hashed_non_unique< boost::multi_index::tag< OptionIdIndexTag >, boost::multi_index::const_mem_fun< data::BaseStampedElement, uint64_t, &data::BaseStampedElement::getId > > > > OptionDefContainer
Multi index container for DHCP option definitions.
boost::shared_ptr< CalloutHandle > CalloutHandlePtr
A shared pointer to a CalloutHandle object.
bool hasObjectId(const db::AuditEntryCollection &audit_entries, const uint64_t &object_id)
Checks if an object is in a collection od audit entries.
Defines the logger used by the top-level component of kea-lfc.
Tag used to access index by object type.