Kea 2.5.5
ca_process.cc
Go to the documentation of this file.
1// Copyright (C) 2016-2023 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
9#include <agent/ca_process.h>
10#include <agent/ca_controller.h>
12#include <agent/ca_log.h>
13#include <asiolink/io_address.h>
14#include <asiolink/io_error.h>
16#include <config/timeouts.h>
17#include <boost/pointer_cast.hpp>
18
19using namespace isc::asiolink;
20using namespace isc::config;
21using namespace isc::data;
22using namespace isc::http;
23using namespace isc::process;
24
25
26namespace isc {
27namespace agent {
28
30 const asiolink::IOServicePtr& io_service)
31 : DProcessBase(name, io_service, DCfgMgrBasePtr(new CtrlAgentCfgMgr())),
32 http_listeners_() {
33}
34
36}
37
38void
40}
41
42void
45
46 try {
47 // Register commands.
48 CtrlAgentControllerPtr controller =
49 boost::dynamic_pointer_cast<CtrlAgentController>(
51 controller->registerCommands();
52
53 // Let's process incoming data or expiring timers in a loop until
54 // shutdown condition is detected.
55 while (!shouldShutdown()) {
56 // Remove unused listeners within the main loop because new listeners
57 // are created in within a callback method. This avoids removal the
58 // listeners within a callback.
59 garbageCollectListeners(1);
60 runIO();
61 }
62 // Done so removing all listeners.
63 garbageCollectListeners(0);
65 } catch (const std::exception& ex) {
67 try {
69 } catch (...) {
70 // Ignore double errors
71 }
73 "Process run method failed: " << ex.what());
74 }
75
76 try {
77 // Deregister commands.
78 CtrlAgentControllerPtr controller =
79 boost::dynamic_pointer_cast<CtrlAgentController>(
81 controller->deregisterCommands();
82 } catch (const std::exception&) {
83 // What to do? Simply ignore...
84 }
85
87}
88
89size_t
90CtrlAgentProcess::runIO() {
91 size_t cnt = getIoService()->get_io_service().poll();
92 if (!cnt) {
93 cnt = getIoService()->get_io_service().run_one();
94 }
95 return (cnt);
96}
97
100 setShutdownFlag(true);
102 "Control Agent is shutting down"));
103}
104
107 bool check_only) {
108 // System reconfiguration often poses an interesting issue whereby the
109 // configuration parsing is successful, but an attempt to use a new
110 // configuration is not. This will leave us in the inconsistent state
111 // when the configuration is in fact only partially applied and the
112 // system's ability to operate is impaired. The use of C++ lambda is
113 // a way to resolve this problem by injecting the code to the
114 // simpleParseConfig which performs an attempt to open new instance
115 // of the listener (if required). The lambda code will throw an
116 // exception if it fails and cause the simpleParseConfig to rollback
117 // configuration changes and report an error.
118 ConstElementPtr answer = getCfgMgr()->simpleParseConfig(config_set,
119 check_only,
120 [this]() {
121 ConfigPtr base_ctx = getCfgMgr()->getContext();
123 ctx = boost::dynamic_pointer_cast<CtrlAgentCfgContext>(base_ctx);
124
125 if (!ctx) {
126 isc_throw(Unexpected, "Internal logic error: bad context type");
127 }
128
130 IOAddress server_address("::");
131 try {
132 server_address = IOAddress(ctx->getHttpHost());
133
134 } catch (const IOError& e) {
135 isc_throw(BadValue, "Failed to convert " << ctx->getHttpHost()
136 << " to IP address:" << e.what());
137 }
138
139 uint16_t server_port = ctx->getHttpPort();
140 bool use_https = false;
141
142 // Only open a new listener if the configuration has changed.
143 if (http_listeners_.empty() ||
144 (http_listeners_.back()->getLocalAddress() != server_address) ||
145 (http_listeners_.back()->getLocalPort() != server_port)) {
146 // Create a TLS context.
147 TlsContextPtr tls_context;
148 // When TLS is enabled configure it.
149 if (!ctx->getCertFile().empty()) {
150 TlsContext::configure(tls_context,
152 ctx->getTrustAnchor(),
153 ctx->getCertFile(),
154 ctx->getKeyFile(),
155 ctx->getCertRequired());
156 use_https = true;
157 }
158
159 // Create response creator factory first. It will be used to
160 // generate response creators. Each response creator will be
161 // used to generate answer to specific request.
163
164 // Create http listener. It will open up a TCP socket and be
165 // prepared to accept incoming connection.
166 HttpListenerPtr http_listener
167 (new HttpListener(*getIoService(), server_address,
168 server_port, tls_context, rcf,
171
172 // Instruct the http listener to actually open socket, install
173 // callback and start listening.
174 http_listener->start();
175
176 // The new listener is running so add it to the collection of
177 // active listeners. The next step will be to remove all other
178 // active listeners, but we do it inside the main process loop.
179 http_listeners_.push_back(http_listener);
180 }
181
182 // Ok, seems we're good to go.
183 if (use_https) {
185 .arg(server_address.toText()).arg(server_port);
186 } else {
188 .arg(server_address.toText()).arg(server_port);
189 }
190 });
191
192 int rcode = 0;
193 config::parseAnswer(rcode, answer);
194 return (answer);
195}
196
197void
198CtrlAgentProcess::garbageCollectListeners(size_t leaving) {
199 // We expect only one active listener. If there are more (most likely 2),
200 // it means we have just reconfigured the server and need to shut down all
201 // listeners except the most recently added.
202 if (http_listeners_.size() > leaving) {
203 // Stop no longer used listeners.
204 for (auto l = http_listeners_.begin();
205 l != http_listeners_.end() - leaving;
206 ++l) {
207 (*l)->stop();
208 }
209 // We have stopped listeners but there may be some pending handlers
210 // related to these listeners. Need to invoke these handlers.
211 getIoService()->get_io_service().poll();
212 // Finally, we're ready to remove no longer used listeners.
213 http_listeners_.erase(http_listeners_.begin(),
214 http_listeners_.end() - leaving);
215 }
216}
217
218
221 return (boost::dynamic_pointer_cast<CtrlAgentCfgMgr>(getCfgMgr()));
222}
223
226 // Return the most recent listener or null.
227 return (http_listeners_.empty() ? ConstHttpListenerPtr() :
228 http_listeners_.back());
229}
230
231bool
233 // If there are is a listener, we're listening.
234 return (static_cast<bool>(getHttpListener()));
235}
236
237} // namespace isc::agent
238} // namespace isc
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown when an unexpected error condition occurs.
Ctrl Agent Configuration Manager.
Definition: ca_cfg_mgr.h:253
static process::DControllerBasePtr & instance()
Static singleton instance method.
bool isListening() const
Checks if the process is listening to the HTTP requests.
Definition: ca_process.cc:232
virtual isc::data::ConstElementPtr shutdown(isc::data::ConstElementPtr args)
Initiates the process's shutdown process.
Definition: ca_process.cc:99
virtual ~CtrlAgentProcess()
Destructor.
Definition: ca_process.cc:35
http::ConstHttpListenerPtr getHttpListener() const
Returns a const pointer to the HTTP listener used by the process.
Definition: ca_process.cc:225
CtrlAgentProcess(const char *name, const asiolink::IOServicePtr &io_service)
Constructor.
Definition: ca_process.cc:29
virtual void init()
Initialize the Control Agent process.
Definition: ca_process.cc:39
CtrlAgentCfgMgrPtr getCtrlAgentCfgMgr()
Returns a pointer to the configuration manager.
Definition: ca_process.cc:220
virtual isc::data::ConstElementPtr configure(isc::data::ConstElementPtr config_set, bool check_only=false)
Processes the given configuration.
Definition: ca_process.cc:106
virtual void run()
Implements the process's event loop.
Definition: ca_process.cc:43
HTTP response creator factory for Control Agent.
HTTP listener.
Definition: listener.h:52
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:160
void stopIOService()
Convenience method for stopping IOservice processing.
Definition: d_process.h:182
asiolink::IOServicePtr & getIoService()
Fetches the controller's IOService.
Definition: d_process.h:174
bool shouldShutdown() const
Checks if the process has been instructed to shut down.
Definition: d_process.h:153
DCfgMgrBasePtr & getCfgMgr()
Fetches the process's configuration manager.
Definition: d_process.h:189
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_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition: macros.h:20
#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
boost::shared_ptr< CtrlAgentCfgContext > CtrlAgentCfgContextPtr
Pointer to a configuration context.
Definition: ca_cfg_mgr.h:23
const isc::log::MessageID CTRL_AGENT_HTTP_SERVICE_STARTED
Definition: ca_messages.h:20
const isc::log::MessageID CTRL_AGENT_STARTED
Definition: ca_messages.h:22
isc::log::Logger agent_logger("ctrl-agent")
Control Agent logger.
Definition: ca_log.h:18
boost::shared_ptr< CtrlAgentCfgMgr > CtrlAgentCfgMgrPtr
Defines a shared pointer to CtrlAgentCfgMgr.
Definition: ca_cfg_mgr.h:311
boost::shared_ptr< CtrlAgentController > CtrlAgentControllerPtr
Definition: ca_controller.h:80
const isc::log::MessageID CTRL_AGENT_HTTPS_SERVICE_STARTED
Definition: ca_messages.h:19
const isc::log::MessageID CTRL_AGENT_RUN_EXIT
Definition: ca_messages.h:21
const isc::log::MessageID CTRL_AGENT_FAILED
Definition: ca_messages.h:18
constexpr long TIMEOUT_AGENT_IDLE_CONNECTION_TIMEOUT
Timeout for the idle connection to be closed.
Definition: timeouts.h:24
ConstElementPtr createAnswer(const int status_code, const std::string &text, const ConstElementPtr &arg)
ConstElementPtr parseAnswer(int &rcode, const ConstElementPtr &msg)
const int CONTROL_RESULT_SUCCESS
Status code indicating a successful operation.
constexpr long TIMEOUT_AGENT_RECEIVE_COMMAND
Timeout for the Control Agent to receive command over the RESTful interface.
Definition: timeouts.h:21
boost::shared_ptr< const Element > ConstElementPtr
Definition: data.h:29
boost::shared_ptr< const HttpListener > ConstHttpListenerPtr
Pointer to the const HttpListener.
Definition: listener.h:142
boost::shared_ptr< HttpListener > HttpListenerPtr
Pointer to the HttpListener.
Definition: listener.h:139
boost::shared_ptr< HttpResponseCreatorFactory > HttpResponseCreatorFactoryPtr
Pointer to the HttpResponseCreatorFactory.
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...
Definition: log_dbglevels.h:50
boost::shared_ptr< DCfgMgrBase > DCfgMgrBasePtr
Defines a shared pointer to DCfgMgrBase.
Definition: d_cfg_mgr.h:247
boost::shared_ptr< ConfigBase > ConfigPtr
Non-const pointer to the ConfigBase.
Definition: config_base.h:176
Defines the logger used by the top-level component of kea-lfc.
Idle connection timeout.
Definition: listener.h:67
HTTP request timeout value.
Definition: listener.h:56