Kea 2.7.5
d2_process.cc
Go to the documentation of this file.
1// Copyright (C) 2013-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>
11#include <config/command_mgr.h>
14#include <d2/d2_controller.h>
15#include <d2/d2_process.h>
16#include <d2srv/d2_cfg_mgr.h>
17#include <d2srv/d2_log.h>
18#include <d2srv/d2_stats.h>
19#include <d2srv/d2_tsig_key.h>
20#include <hooks/hooks.h>
21#include <hooks/hooks_manager.h>
22
23using namespace isc::asiolink;
24using namespace isc::config;
25using namespace isc::hooks;
26using namespace isc::process;
27
28namespace {
29
31struct D2ProcessHooks {
32 int hooks_index_d2_srv_configured_;
33
35 D2ProcessHooks() {
36 hooks_index_d2_srv_configured_ = HooksManager::registerHook("d2_srv_configured");
37 }
38
39};
40
41// Declare a Hooks object. As this is outside any function or method, it
42// will be instantiated (and the constructor run) when the module is loaded.
43// As a result, the hook indexes will be defined before any method in this
44// module is called.
45D2ProcessHooks Hooks;
46
47}
48
49namespace isc {
50namespace d2 {
51
52// Setting to 80% for now. This is an arbitrary choice and should probably
53// be configurable.
54const unsigned int D2Process::QUEUE_RESTART_PERCENT = 80;
55
56D2Process::D2Process(const char* name, const asiolink::IOServicePtr& io_service)
57 : DProcessBase(name, io_service, DCfgMgrBasePtr(new D2CfgMgr())),
58 reconf_queue_flag_(false), shutdown_type_(SD_NORMAL) {
59
60 // Instantiate queue manager. Note that queue manager does not start
61 // listening at this point. That can only occur after configuration has
62 // been received. This means that until we receive the configuration,
63 // D2 will neither receive nor process NameChangeRequests.
64 // Pass in IOService for NCR IO event processing.
65 queue_mgr_.reset(new D2QueueMgr(getIOService()));
66
67 // Instantiate update manager.
68 // Pass in both queue manager and configuration manager.
69 // Pass in IOService for DNS update transaction IO event processing.
71 update_mgr_.reset(new D2UpdateMgr(queue_mgr_, tmp, getIOService()));
72
73 // Initialize stats manager.
75};
76
77void
79 using namespace isc::config;
80 // Command managers use IO service to run asynchronous socket operations.
81 UnixCommandMgr::instance().setIOService(getIOService());
82 HttpCommandMgr::instance().setIOService(getIOService());
83
84 // Set the HTTP authentication default realm.
86
87 // D2 server does not use the interface manager.
88 UnixCommandMgr::instance().addExternalSockets(false);
89 HttpCommandMgr::instance().addExternalSockets(false);
90};
91
92void
95 D2ControllerPtr controller =
96 boost::dynamic_pointer_cast<D2Controller>(D2Controller::instance());
97 try {
98 // Now logging was initialized so commands can be registered.
99 controller->registerCommands();
100
101 // Loop forever until we are allowed to shutdown.
102 while (!canShutdown()) {
103 // Check on the state of the request queue. Take any
104 // actions necessary regarding it.
106
107 // Give update manager a time slice to queue new jobs and
108 // process finished ones.
109 update_mgr_->sweep();
110
111 // Wait on IO event(s) - block until one or more of the following
112 // has occurred:
113 // a. NCR message has been received
114 // b. Transaction IO has completed
115 // c. Interval timer expired
116 // d. Control channel event
117 // e. Something stopped IO service (runIO returns 0)
118 if (runIO() == 0) {
119 // Pretty sure this amounts to an unexpected stop and we
120 // should bail out now. Normal shutdowns do not utilize
121 // stopping the IOService.
123 "Primary IO service stopped unexpectedly");
124 }
125 }
126 } catch (const std::exception& ex) {
127 LOG_FATAL(d2_logger, DHCP_DDNS_FAILED).arg(ex.what());
128 controller->deregisterCommands();
130 "Process run method failed: " << ex.what());
131 }
132
136
137 controller->deregisterCommands();
138
140
141};
142
143size_t
145 // Handle events registered by hooks using external IOService objects.
146 IOServiceMgr::instance().pollIOServices();
147 // We want to block until at least one handler is called. We'll use
148 // boost::asio::io_service directly for two reasons. First off
149 // asiolink::IOService::runOne is a void and boost::asio::io_service::stopped
150 // is not present in older versions of boost. We need to know if any
151 // handlers ran or if the io_service was stopped. That latter represents
152 // some form of error and the application cannot proceed with a stopped
153 // service. Secondly, asiolink::IOService does not provide the poll
154 // method. This is a handy method which runs all ready handlers without
155 // blocking.
156
157 // Poll runs all that are ready. If none are ready it returns immediately
158 // with a count of zero.
159 size_t cnt = getIOService()->poll();
160 if (!cnt) {
161 // Poll ran no handlers either none are ready or the service has been
162 // stopped. Either way, call runOne to wait for a IO event. If the
163 // service is stopped it will return immediately with a cnt of zero.
164 cnt = getIOService()->runOne();
165 }
166 HttpCommandMgr::instance().garbageCollectListeners();
167 return (cnt);
168}
169
170bool
172 bool all_clear = false;
173
174 // If we have been told to shutdown, find out if we are ready to do so.
175 if (shouldShutdown()) {
176 switch (shutdown_type_) {
177 case SD_NORMAL:
178 // For a normal shutdown we need to stop the queue manager but
179 // wait until we have finished all the transactions in progress.
180 all_clear = (((queue_mgr_->getMgrState() != D2QueueMgr::RUNNING) &&
181 (queue_mgr_->getMgrState() != D2QueueMgr::STOPPING))
182 && (update_mgr_->getTransactionCount() == 0));
183 break;
184
185 case SD_DRAIN_FIRST:
186 // For a drain first shutdown we need to stop the queue manager but
187 // process all of the requests in the receive queue first.
188 all_clear = (((queue_mgr_->getMgrState() != D2QueueMgr::RUNNING) &&
189 (queue_mgr_->getMgrState() != D2QueueMgr::STOPPING))
190 && (queue_mgr_->getQueueSize() == 0)
191 && (update_mgr_->getTransactionCount() == 0));
192 break;
193
194 case SD_NOW:
195 // Get out right now, no niceties.
196 all_clear = true;
197 break;
198
199 default:
200 // shutdown_type_ is an enum and should only be one of the above.
201 // if its getting through to this, something is whacked.
202 break;
203 }
204
205 if (all_clear) {
208 .arg(getShutdownTypeStr(shutdown_type_));
209 }
210 }
211
212 return (all_clear);
213}
214
219 .arg(args ? args->str() : "(no arguments)");
220
221 // Default shutdown type is normal.
222 std::string type_str(getShutdownTypeStr(SD_NORMAL));
223 shutdown_type_ = SD_NORMAL;
224
225 if (args) {
226 if ((args->getType() == isc::data::Element::map) &&
227 args->contains("type")) {
228 type_str = args->get("type")->stringValue();
229
230 if (type_str == getShutdownTypeStr(SD_NORMAL)) {
231 shutdown_type_ = SD_NORMAL;
232 } else if (type_str == getShutdownTypeStr(SD_DRAIN_FIRST)) {
233 shutdown_type_ = SD_DRAIN_FIRST;
234 } else if (type_str == getShutdownTypeStr(SD_NOW)) {
235 shutdown_type_ = SD_NOW;
236 } else {
237 setShutdownFlag(false);
239 "Invalid Shutdown type: " +
240 type_str));
241 }
242 }
243 }
244
245 // Set the base class's shutdown flag.
246 setShutdownFlag(true);
248 "Shutdown initiated, type is: " +
249 type_str));
250}
251
255 .arg(check_only ? "check" : "update")
256 .arg(getD2CfgMgr()->redactConfig(config_set)->str());
257
259 answer = getCfgMgr()->simpleParseConfig(config_set, check_only,
260 std::bind(&D2Process::reconfigureCommandChannel, this));
261 if (check_only) {
262 return (answer);
263 }
264
265 int rcode = 0;
267 comment = isc::config::parseAnswer(rcode, answer);
268
269 if (rcode) {
270 // Non-zero means we got an invalid configuration, take no further
271 // action. In integrated mode, this will send a failed response back
272 // to the configuration backend.
273 reconf_queue_flag_ = false;
274 return (answer);
275 }
276
277 // Set the reconf_queue_flag to indicate that we need to reconfigure
278 // the queue manager. Reconfiguring the queue manager may be asynchronous
279 // and require one or more events to occur, therefore we set a flag
280 // indicating it needs to be done but we cannot do it here. It must
281 // be done over time, while events are being processed. Remember that
282 // the method we are in now is invoked as part of the configuration event
283 // callback. This means you can't wait for events here, you are already
284 // in one.
288 reconf_queue_flag_ = true;
289
290 // This hook point notifies hooks libraries that the configuration of the
291 // D2 server has completed. It provides the hook library with the pointer
292 // to the common IO service object, new server configuration in the JSON
293 // format and with the pointer to the configuration storage where the
294 // parsed configuration is stored.
295 std::string error("");
296 if (HooksManager::calloutsPresent(Hooks.hooks_index_d2_srv_configured_)) {
298
299 callout_handle->setArgument("io_context", getIOService());
300 callout_handle->setArgument("json_config", config_set);
301 callout_handle->setArgument("server_config",
302 getD2CfgMgr()->getD2CfgContext());
303 callout_handle->setArgument("error", error);
304
305 HooksManager::callCallouts(Hooks.hooks_index_d2_srv_configured_,
306 *callout_handle);
307
308 // The config can be rejected by a hook.
309 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
310 callout_handle->getArgument("error", error);
312 .arg(error);
313 reconf_queue_flag_ = false;
315 return (answer);
316 }
317 }
318
320 try {
321 // Handle events registered by hooks using external IOService objects.
322 IOServiceMgr::instance().pollIOServices();
323 } catch (const std::exception& ex) {
324 std::ostringstream err;
325 err << "Error initializing hooks: "
326 << ex.what();
328 }
329
330 // If we are here, configuration was valid, at least it parsed correctly
331 // and therefore contained no invalid values.
332 // Return the success answer from above.
333 return (answer);
334}
335
336void
338 switch (queue_mgr_->getMgrState()){
340 if (reconf_queue_flag_ || shouldShutdown()) {
345 try {
348 .arg(reconf_queue_flag_ ? "reconfiguration" : "shutdown");
349 queue_mgr_->stopListening();
350 } catch (const isc::Exception& ex) {
351 // It is very unlikely that we would experience an error
352 // here, but theoretically possible.
354 .arg(ex.what());
355 }
356 }
357 break;
358
363 size_t threshold = (((queue_mgr_->getMaxQueueSize()
364 * QUEUE_RESTART_PERCENT)) / 100);
365 if (queue_mgr_->getQueueSize() <= threshold) {
367 .arg(threshold).arg(queue_mgr_->getMaxQueueSize());
368 try {
369 queue_mgr_->startListening();
370 } catch (const isc::Exception& ex) {
372 .arg(ex.what());
373 }
374 }
375
376 break;
377 }
378
387 if (!shouldShutdown()) {
390 }
391 break;
392
398 break;
399
400 default:
401 // If the reconfigure flag is set, then we are in a state now where
402 // we can do the reconfigure. In other words, we aren't RUNNING or
403 // STOPPING.
404 if (reconf_queue_flag_) {
408 }
409 break;
410 }
411}
412
413void
415 // Set reconfigure flag to false. We are only here because we have
416 // a valid configuration to work with so if we fail below, it will be
417 // an operational issue, such as a busy IP address. That will leave
418 // queue manager in INITTED state, which is fine.
419 // What we don't want is to continually attempt to reconfigure so set
420 // the flag false now.
424 reconf_queue_flag_ = false;
425 try {
426 // Wipe out the current listener.
427 queue_mgr_->removeListener();
428
429 // Get the configuration parameters that affect Queue Manager.
430 const D2ParamsPtr& d2_params = getD2CfgMgr()->getD2Params();
431
434 std::string ip_address = d2_params->getIpAddress().toText();
435 if (ip_address == "0.0.0.0" || ip_address == "::") {
437 } else if (ip_address != "127.0.0.1" && ip_address != "::1") {
439 }
440
441 // Instantiate the listener.
442 if (d2_params->getNcrProtocol() == dhcp_ddns::NCR_UDP) {
443 queue_mgr_->initUDPListener(d2_params->getIpAddress(),
444 d2_params->getPort(),
445 d2_params->getNcrFormat(), true);
446 } else {
448 // We should never get this far but if we do deal with it.
449 isc_throw(DProcessBaseError, "Unsupported NCR listener protocol:"
450 << dhcp_ddns::ncrProtocolToString(d2_params->
451 getNcrProtocol()));
452 }
453
454 // Now start it. This assumes that starting is a synchronous,
455 // blocking call that executes quickly.
458 queue_mgr_->startListening();
459 } catch (const isc::Exception& ex) {
460 // Queue manager failed to initialize and therefore not listening.
461 // This is most likely due to an unavailable IP address or port,
462 // which is a configuration issue.
464 }
465}
466
468 queue_mgr_->stopListening();
469 getIOService()->stopAndPoll();
470 queue_mgr_->removeListener();
471}
472
475 // The base class gives a base class pointer to our configuration manager.
476 // Since we are D2, and we need D2 specific extensions, we need a pointer
477 // to D2CfgMgr for some things.
478 return (boost::dynamic_pointer_cast<D2CfgMgr>(getCfgMgr()));
479}
480
482 const char* str;
483 switch (type) {
484 case SD_NORMAL:
485 str = "normal";
486 break;
487 case SD_DRAIN_FIRST:
488 str = "drain_first";
489 break;
490 case SD_NOW:
491 str = "now";
492 break;
493 default:
494 str = "invalid";
495 break;
496 }
497
498 return (str);
499}
500
501void
503 // Get new Unix socket configuration.
505 getD2CfgMgr()->getUnixControlSocketInfo();
506
507 // Determine if the socket configuration has changed. It has if
508 // both old and new configuration is specified but respective
509 // data elements aren't equal.
510 bool sock_changed = (sock_cfg && current_control_socket_ &&
511 !sock_cfg->equals(*current_control_socket_));
512
513 // If the previous or new socket configuration doesn't exist or
514 // the new configuration differs from the old configuration we
515 // close the existing socket and open a new socket as appropriate.
516 // Note that closing an existing socket means the client will not
517 // receive the configuration result.
518 if (!sock_cfg || !current_control_socket_ || sock_changed) {
519 // Close the existing socket.
520 if (current_control_socket_) {
521 UnixCommandMgr::instance().closeCommandSocket();
522 current_control_socket_.reset();
523 }
524
525 // Open the new socket.
526 if (sock_cfg) {
527 UnixCommandMgr::instance().openCommandSocket(sock_cfg);
528 }
529 }
530
531 // Commit the new socket configuration.
532 current_control_socket_ = sock_cfg;
533
534 // HTTP control socket is simpler: just (re)configure it.
535
536 // Get new config.
537 HttpCommandConfigPtr http_config =
538 getD2CfgMgr()->getHttpControlSocketInfo();
539 HttpCommandMgr::instance().configure(http_config);
540}
541
542} // namespace isc::d2
543} // namespace isc
CtrlAgentHooks Hooks
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.
static std::string DEFAULT_AUTHENTICATION_REALM
Default HTTP authentication realm.
static HttpCommandMgr & instance()
HttpCommandMgr is a singleton class.
static UnixCommandMgr & instance()
UnixCommandMgr is a singleton class.
DHCP-DDNS Configuration Manager.
Definition d2_cfg_mgr.h:183
static process::DControllerBasePtr & instance()
Static singleton instance method.
D2Process(const char *name, const asiolink::IOServicePtr &io_service)
Constructor.
Definition d2_process.cc:56
static const unsigned int QUEUE_RESTART_PERCENT
Defines the point at which to resume receiving requests.
Definition d2_process.h:48
virtual bool canShutdown() const
Indicates whether or not the process can perform a shutdown.
virtual void checkQueueStatus()
Monitors current queue manager state, takes action accordingly.
virtual ~D2Process()
Destructor.
virtual void run()
Implements the process's event loop.
Definition d2_process.cc:93
virtual void init()
Called after instantiation to perform initialization unique to D2.
Definition d2_process.cc:78
D2CfgMgrPtr getD2CfgMgr()
Returns a pointer to the configuration manager.
virtual isc::data::ConstElementPtr configure(isc::data::ConstElementPtr config_set, bool check_only=false)
Processes the given configuration.
void reconfigureCommandChannel()
(Re-)Configure the command channel.
virtual void reconfigureQueueMgr()
Initializes then starts the queue manager.
ShutdownType
Defines the shutdown types supported by D2Process.
Definition d2_process.h:36
virtual isc::data::ConstElementPtr shutdown(isc::data::ConstElementPtr args)
Initiates the D2Process shutdown process.
static const char * getShutdownTypeStr(const ShutdownType &type)
Returns a text label for the given shutdown type.
virtual size_t runIO()
Allows IO processing to run until at least callback is invoked.
D2QueueMgr creates and manages a queue of DNS update requests.
static void init()
Initialize D2 statistics.
Definition d2_stats.cc:47
D2UpdateMgr creates and manages update transactions.
@ NEXT_STEP_DROP
drop the packet
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.
Exception thrown if the process encountered an operational error.
Definition d_process.h:24
Application Process Interface.
Definition d_process.h:75
void setShutdownFlag(bool value)
Sets the process shut down flag to the given value.
Definition d_process.h:162
bool shouldShutdown() const
Checks if the process has been instructed to shut down.
Definition d_process.h:155
asiolink::IOServicePtr & getIOService()
Fetches the controller's IOService.
Definition d_process.h:176
DCfgMgrBasePtr & getCfgMgr()
Fetches the process's configuration manager.
Definition d_process.h:191
This file contains several functions and constants that are used for handling commands and responses ...
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
#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_FATAL(LOGGER, MESSAGE)
Macro to conveniently test fatal output and log it.
Definition macros.h:38
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition macros.h:14
const int CONTROL_RESULT_ERROR
Status code indicating a general failure.
ConstElementPtr createAnswer()
Creates a standard config/command level success answer message (i.e.
ConstElementPtr parseAnswer(int &rcode, const ConstElementPtr &msg)
boost::shared_ptr< HttpCommandConfig > HttpCommandConfigPtr
Pointer to a HttpCommandConfig object.
const int CONTROL_RESULT_SUCCESS
Status code indicating a successful operation.
boost::shared_ptr< D2CfgMgr > D2CfgMgrPtr
Defines a shared pointer to D2CfgMgr.
Definition d2_cfg_mgr.h:367
const isc::log::MessageID DHCP_DDNS_QUEUE_MGR_RECOVERING
Definition d2_messages.h:56
const isc::log::MessageID DHCP_DDNS_QUEUE_MGR_STOP_ERROR
Definition d2_messages.h:64
const isc::log::MessageID DHCP_DDNS_FAILED
Definition d2_messages.h:20
const isc::log::MessageID DHCP_DDNS_LISTENING_ON_ALL_INTERFACES
Definition d2_messages.h:47
const isc::log::MessageID DHCP_DDNS_QUEUE_MGR_START_ERROR
Definition d2_messages.h:61
const isc::log::MessageID DHCP_DDNS_SHUTDOWN_COMMAND
Definition d2_messages.h:84
const isc::log::MessageID DHCP_DDNS_CONFIGURE
Definition d2_messages.h:15
const isc::log::MessageID DHCP_DDNS_CLEARED_FOR_SHUTDOWN
Definition d2_messages.h:14
const isc::log::MessageID DHCP_DDNS_QUEUE_MGR_RECONFIGURING
Definition d2_messages.h:55
const isc::log::MessageID DHCP_DDNS_RUN_EXIT
Definition d2_messages.h:83
const isc::log::MessageID DHCP_DDNS_CONFIGURED_CALLOUT_DROP
Definition d2_messages.h:16
const isc::log::MessageID DHCP_DDNS_QUEUE_MGR_RESUME_ERROR
Definition d2_messages.h:58
const isc::log::MessageID DHCP_DDNS_STARTED
Definition d2_messages.h:85
boost::shared_ptr< D2Controller > D2ControllerPtr
Pointer to a process controller.
isc::log::Logger d2_logger("dhcpddns")
Defines the logger used within D2.
Definition d2_log.h:18
const isc::log::MessageID DHCP_DDNS_QUEUE_MGR_RESUMING
Definition d2_messages.h:59
boost::shared_ptr< D2Params > D2ParamsPtr
Defines a pointer for D2Params instances.
Definition d2_config.h:257
const isc::log::MessageID DHCP_DDNS_QUEUE_MGR_STOPPING
Definition d2_messages.h:63
const isc::log::MessageID DHCP_DDNS_NOT_ON_LOOPBACK
Definition d2_messages.h:48
boost::shared_ptr< const Element > ConstElementPtr
Definition data.h:29
std::string ncrProtocolToString(NameChangeProtocol protocol)
Function which converts NameChangeProtocol enums to text labels.
Definition ncr_io.cc:36
boost::shared_ptr< CalloutHandle > CalloutHandlePtr
A shared pointer to a CalloutHandle object.
const int DBGLVL_TRACE_BASIC
Trace basic operations.
const int DBGLVL_START_SHUT
This is given a value of 0 as that is the level selected if debugging is enabled without giving a lev...
boost::shared_ptr< DCfgMgrBase > DCfgMgrBasePtr
Defines a shared pointer to DCfgMgrBase.
Definition d_cfg_mgr.h:247
Defines the logger used by the top-level component of kea-lfc.