Kea 2.7.6
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.
83
84 // Set the HTTP authentication default realm.
86
87 // D2 server does not use the interface manager.
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.
147 // We want to block until at least one handler is called.
148 // Poll runs all that are ready. If none are ready it returns immediately
149 // with a count of zero.
150 size_t cnt = getIOService()->poll();
151 if (!cnt) {
152 // Poll ran no handlers either none are ready or the service has been
153 // stopped. Either way, call runOne to wait for a IO event. If the
154 // service is stopped it will return immediately with a cnt of zero.
155 cnt = getIOService()->runOne();
156 }
158 return (cnt);
159}
160
161bool
163 bool all_clear = false;
164
165 // If we have been told to shutdown, find out if we are ready to do so.
166 if (shouldShutdown()) {
167 switch (shutdown_type_) {
168 case SD_NORMAL:
169 // For a normal shutdown we need to stop the queue manager but
170 // wait until we have finished all the transactions in progress.
171 all_clear = (((queue_mgr_->getMgrState() != D2QueueMgr::RUNNING) &&
172 (queue_mgr_->getMgrState() != D2QueueMgr::STOPPING))
173 && (update_mgr_->getTransactionCount() == 0));
174 break;
175
176 case SD_DRAIN_FIRST:
177 // For a drain first shutdown we need to stop the queue manager but
178 // process all of the requests in the receive queue first.
179 all_clear = (((queue_mgr_->getMgrState() != D2QueueMgr::RUNNING) &&
180 (queue_mgr_->getMgrState() != D2QueueMgr::STOPPING))
181 && (queue_mgr_->getQueueSize() == 0)
182 && (update_mgr_->getTransactionCount() == 0));
183 break;
184
185 case SD_NOW:
186 // Get out right now, no niceties.
187 all_clear = true;
188 break;
189
190 default:
191 // shutdown_type_ is an enum and should only be one of the above.
192 // if its getting through to this, something is whacked.
193 break;
194 }
195
196 if (all_clear) {
199 .arg(getShutdownTypeStr(shutdown_type_));
200 }
201 }
202
203 return (all_clear);
204}
205
210 .arg(args ? args->str() : "(no arguments)");
211
212 // Default shutdown type is normal.
213 std::string type_str(getShutdownTypeStr(SD_NORMAL));
214 shutdown_type_ = SD_NORMAL;
215
216 if (args) {
217 if ((args->getType() == isc::data::Element::map) &&
218 args->contains("type")) {
219 type_str = args->get("type")->stringValue();
220
221 if (type_str == getShutdownTypeStr(SD_NORMAL)) {
222 shutdown_type_ = SD_NORMAL;
223 } else if (type_str == getShutdownTypeStr(SD_DRAIN_FIRST)) {
224 shutdown_type_ = SD_DRAIN_FIRST;
225 } else if (type_str == getShutdownTypeStr(SD_NOW)) {
226 shutdown_type_ = SD_NOW;
227 } else {
228 setShutdownFlag(false);
230 "Invalid Shutdown type: " +
231 type_str));
232 }
233 }
234 }
235
236 // Set the base class's shutdown flag.
237 setShutdownFlag(true);
239 "Shutdown initiated, type is: " +
240 type_str));
241}
242
246 .arg(check_only ? "check" : "update")
247 .arg(getD2CfgMgr()->redactConfig(config_set)->str());
248
250 answer = getCfgMgr()->simpleParseConfig(config_set, check_only,
251 std::bind(&D2Process::reconfigureCommandChannel, this));
252 if (check_only) {
253 return (answer);
254 }
255
256 int rcode = 0;
258 comment = isc::config::parseAnswer(rcode, answer);
259
260 if (rcode) {
261 // Non-zero means we got an invalid configuration, take no further
262 // action. In integrated mode, this will send a failed response back
263 // to the configuration backend.
264 reconf_queue_flag_ = false;
265 return (answer);
266 }
267
268 // Set the reconf_queue_flag to indicate that we need to reconfigure
269 // the queue manager. Reconfiguring the queue manager may be asynchronous
270 // and require one or more events to occur, therefore we set a flag
271 // indicating it needs to be done but we cannot do it here. It must
272 // be done over time, while events are being processed. Remember that
273 // the method we are in now is invoked as part of the configuration event
274 // callback. This means you can't wait for events here, you are already
275 // in one.
279 reconf_queue_flag_ = true;
280
281 // This hook point notifies hooks libraries that the configuration of the
282 // D2 server has completed. It provides the hook library with the pointer
283 // to the common IO service object, new server configuration in the JSON
284 // format and with the pointer to the configuration storage where the
285 // parsed configuration is stored.
286 std::string error("");
287 if (HooksManager::calloutsPresent(Hooks.hooks_index_d2_srv_configured_)) {
289
290 callout_handle->setArgument("io_context", getIOService());
291 callout_handle->setArgument("json_config", config_set);
292 callout_handle->setArgument("server_config",
293 getD2CfgMgr()->getD2CfgContext());
294 callout_handle->setArgument("error", error);
295
296 HooksManager::callCallouts(Hooks.hooks_index_d2_srv_configured_,
297 *callout_handle);
298
299 // The config can be rejected by a hook.
300 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
301 callout_handle->getArgument("error", error);
303 .arg(error);
304 reconf_queue_flag_ = false;
306 return (answer);
307 }
308 }
309
311 try {
312 // Handle events registered by hooks using external IOService objects.
314 } catch (const std::exception& ex) {
315 std::ostringstream err;
316 err << "Error initializing hooks: "
317 << ex.what();
319 }
320
321 // If we are here, configuration was valid, at least it parsed correctly
322 // and therefore contained no invalid values.
323 // Return the success answer from above.
324 return (answer);
325}
326
327void
329 switch (queue_mgr_->getMgrState()){
331 if (reconf_queue_flag_ || shouldShutdown()) {
336 try {
339 .arg(reconf_queue_flag_ ? "reconfiguration" : "shutdown");
340 queue_mgr_->stopListening();
341 } catch (const isc::Exception& ex) {
342 // It is very unlikely that we would experience an error
343 // here, but theoretically possible.
345 .arg(ex.what());
346 }
347 }
348 break;
349
354 size_t threshold = (((queue_mgr_->getMaxQueueSize()
355 * QUEUE_RESTART_PERCENT)) / 100);
356 if (queue_mgr_->getQueueSize() <= threshold) {
358 .arg(threshold).arg(queue_mgr_->getMaxQueueSize());
359 try {
360 queue_mgr_->startListening();
361 } catch (const isc::Exception& ex) {
363 .arg(ex.what());
364 }
365 }
366
367 break;
368 }
369
378 if (!shouldShutdown()) {
381 }
382 break;
383
389 break;
390
391 default:
392 // If the reconfigure flag is set, then we are in a state now where
393 // we can do the reconfigure. In other words, we aren't RUNNING or
394 // STOPPING.
395 if (reconf_queue_flag_) {
399 }
400 break;
401 }
402}
403
404void
406 // Set reconfigure flag to false. We are only here because we have
407 // a valid configuration to work with so if we fail below, it will be
408 // an operational issue, such as a busy IP address. That will leave
409 // queue manager in INITTED state, which is fine.
410 // What we don't want is to continually attempt to reconfigure so set
411 // the flag false now.
415 reconf_queue_flag_ = false;
416 try {
417 // Wipe out the current listener.
418 queue_mgr_->removeListener();
419
420 // Get the configuration parameters that affect Queue Manager.
421 const D2ParamsPtr& d2_params = getD2CfgMgr()->getD2Params();
422
425 std::string ip_address = d2_params->getIpAddress().toText();
426 if (ip_address == "0.0.0.0" || ip_address == "::") {
428 } else if (ip_address != "127.0.0.1" && ip_address != "::1") {
430 }
431
432 // Instantiate the listener.
433 if (d2_params->getNcrProtocol() == dhcp_ddns::NCR_UDP) {
434 queue_mgr_->initUDPListener(d2_params->getIpAddress(),
435 d2_params->getPort(),
436 d2_params->getNcrFormat(), true);
437 } else {
439 // We should never get this far but if we do deal with it.
440 isc_throw(DProcessBaseError, "Unsupported NCR listener protocol:"
441 << dhcp_ddns::ncrProtocolToString(d2_params->
442 getNcrProtocol()));
443 }
444
445 // Now start it. This assumes that starting is a synchronous,
446 // blocking call that executes quickly.
449 queue_mgr_->startListening();
450 } catch (const isc::Exception& ex) {
451 // Queue manager failed to initialize and therefore not listening.
452 // This is most likely due to an unavailable IP address or port,
453 // which is a configuration issue.
455 }
456}
457
459 queue_mgr_->stopListening();
460 getIOService()->stopAndPoll();
461 queue_mgr_->removeListener();
462}
463
466 // The base class gives a base class pointer to our configuration manager.
467 // Since we are D2, and we need D2 specific extensions, we need a pointer
468 // to D2CfgMgr for some things.
469 return (boost::dynamic_pointer_cast<D2CfgMgr>(getCfgMgr()));
470}
471
473 const char* str;
474 switch (type) {
475 case SD_NORMAL:
476 str = "normal";
477 break;
478 case SD_DRAIN_FIRST:
479 str = "drain_first";
480 break;
481 case SD_NOW:
482 str = "now";
483 break;
484 default:
485 str = "invalid";
486 break;
487 }
488
489 return (str);
490}
491
492void
494 // Get new Unix socket configuration.
496 getD2CfgMgr()->getUnixControlSocketInfo();
497
498 // Determine if the socket configuration has changed. It has if
499 // both old and new configuration is specified but respective
500 // data elements aren't equal.
501 bool sock_changed = (sock_cfg && current_control_socket_ &&
502 !sock_cfg->equals(*current_control_socket_));
503
504 // If the previous or new socket configuration doesn't exist or
505 // the new configuration differs from the old configuration we
506 // close the existing socket and open a new socket as appropriate.
507 // Note that closing an existing socket means the client will not
508 // receive the configuration result.
509 if (!sock_cfg || !current_control_socket_ || sock_changed) {
510 // Close the existing socket.
511 if (current_control_socket_) {
513 current_control_socket_.reset();
514 }
515
516 // Open the new socket.
517 if (sock_cfg) {
519 }
520 }
521
522 // Commit the new socket configuration.
523 current_control_socket_ = sock_cfg;
524
525 // HTTP control socket is simpler: just (re)configure it.
526
527 // Get new config.
528 HttpCommandConfigPtr http_config =
529 getD2CfgMgr()->getHttpControlSocketInfo();
530 HttpCommandMgr::instance().configure(http_config);
531}
532
533} // namespace isc::d2
534} // 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.
void addExternalSockets(bool use_external=true)
Use external sockets flag.
static HttpCommandMgr & instance()
HttpCommandMgr is a singleton class.
void garbageCollectListeners()
Removes listeners which are no longer in use.
void setIOService(const asiolink::IOServicePtr &io_service)
Sets IO service to be used by the http command manager.
void configure(HttpCommandConfigPtr config)
Configure http control socket from configuration.
static UnixCommandMgr & instance()
UnixCommandMgr is a singleton class.
void setIOService(const asiolink::IOServicePtr &io_service)
Sets IO service to be used by the unix command manager.
void closeCommandSocket()
Shuts down any open unix control sockets.
void openCommandSocket(const isc::data::ConstElementPtr &socket_info)
Opens unix control socket with parameters specified in socket_info (required parameters: socket-type:...
void addExternalSockets(bool use_external=true)
Use external sockets flag.
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
ConstElementPtr parseAnswer(int &rcode, const ConstElementPtr &msg)
Parses a standard config/command level answer and returns arguments or text status code.
const int CONTROL_RESULT_ERROR
Status code indicating a general failure.
ConstElementPtr createAnswer()
Creates a standard config/command level success answer message (i.e.
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
ConstElementPtr redactConfig(ConstElementPtr const &element, list< string > const &json_path)
Redact a configuration.
Defines the logger used by the top-level component of kea-lfc.