Kea  1.5.0
ca_process.cc
Go to the documentation of this file.
1 // Copyright (C) 2016-2018 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>
15 #include <cc/command_interpreter.h>
16 #include <config/timeouts.h>
17 #include <boost/pointer_cast.hpp>
18 
19 using namespace isc::asiolink;
20 using namespace isc::config;
21 using namespace isc::data;
22 using namespace isc::http;
23 using namespace isc::process;
24 
25 
26 namespace isc {
27 namespace agent {
28 
29 CtrlAgentProcess::CtrlAgentProcess(const char* name,
30  const asiolink::IOServicePtr& io_service)
31  : DProcessBase(name, io_service, DCfgMgrBasePtr(new CtrlAgentCfgMgr())),
32  http_listeners_() {
33 }
34 
36 }
37 
38 void
40 }
41 
42 void
44  LOG_INFO(agent_logger, CTRL_AGENT_STARTED).arg(VERSION);
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();
60  runIO();
61  }
62  stopIOService();
63  } catch (const std::exception& ex) {
64  LOG_FATAL(agent_logger, CTRL_AGENT_FAILED).arg(ex.what());
65  try {
66  stopIOService();
67  } catch (...) {
68  // Ignore double errors
69  }
71  "Process run method failed: " << ex.what());
72  }
73 
74  try {
75  // Deregister commands.
76  CtrlAgentControllerPtr controller =
77  boost::dynamic_pointer_cast<CtrlAgentController>(
79  controller->deregisterCommands();
80  } catch (const std::exception&) {
81  // What to do? Simply ignore...
82  }
83 
84  LOG_DEBUG(agent_logger, isc::log::DBGLVL_START_SHUT, CTRL_AGENT_RUN_EXIT);
85 }
86 
87 size_t
88 CtrlAgentProcess::runIO() {
89  size_t cnt = getIoService()->get_io_service().poll();
90  if (!cnt) {
91  cnt = getIoService()->get_io_service().run_one();
92  }
93  return (cnt);
94 }
95 
98  setShutdownFlag(true);
99  return (isc::config::createAnswer(0, "Control Agent is shutting down"));
100 }
101 
104  bool check_only) {
105  // System reconfiguration often poses an interesting issue whereby the
106  // configuration parsing is successful, but an attempt to use a new
107  // configuration is not. This will leave us in the inconsistent state
108  // when the configuration is in fact only partially applied and the
109  // system's ability to operate is impaired. The use of C++ lambda is
110  // a way to resolve this problem by injecting the code to the
111  // simpleParseConfig which performs an attempt to open new instance
112  // of the listener (if required). The lambda code will throw an
113  // exception if it fails and cause the simpleParseConfig to rollback
114  // configuration changes and report an error.
115  ConstElementPtr answer = getCfgMgr()->simpleParseConfig(config_set,
116  check_only,
117  [this]() {
118  ConfigPtr base_ctx = getCfgMgr()->getContext();
120  ctx = boost::dynamic_pointer_cast<CtrlAgentCfgContext>(base_ctx);
121 
122  if (!ctx) {
123  isc_throw(Unexpected, "Internal logic error: bad context type");
124  }
125 
127  IOAddress server_address("::");
128  try {
129  server_address = IOAddress(ctx->getHttpHost());
130 
131  } catch (const IOError& e) {
132  isc_throw(BadValue, "Failed to convert " << ctx->getHttpHost()
133  << " to IP address:" << e.what());
134  }
135 
136  uint16_t server_port = ctx->getHttpPort();
137 
138  // Only open a new listener if the configuration has changed.
139  if (http_listeners_.empty() ||
140  (http_listeners_.back()->getLocalAddress() != server_address) ||
141  (http_listeners_.back()->getLocalPort() != server_port)) {
142  // Create response creator factory first. It will be used to
143  // generate response creators. Each response creator will be
144  // used to generate answer to specific request.
146 
147  // Create http listener. It will open up a TCP socket and be
148  // prepared to accept incoming connection.
149  HttpListenerPtr http_listener
150  (new HttpListener(*getIoService(), server_address,
151  server_port, rcf,
154 
155  // Instruct the http listener to actually open socket, install
156  // callback and start listening.
157  http_listener->start();
158 
159  // The new listener is running so add it to the collection of
160  // active listeners. The next step will be to remove all other
161  // active listeners, but we do it inside the main process loop.
162  http_listeners_.push_back(http_listener);
163  }
164 
165  // Ok, seems we're good to go.
166  LOG_INFO(agent_logger, CTRL_AGENT_HTTP_SERVICE_STARTED)
167  .arg(server_address.toText()).arg(server_port);
168 
169  });
170 
171  int rcode = 0;
172  config::parseAnswer(rcode, answer);
173  return (answer);
174 }
175 
176 void
177 CtrlAgentProcess::garbageCollectListeners() {
178  // We expect only one active listener. If there are more (most likely 2),
179  // it means we have just reconfigured the server and need to shut down all
180  // listeners execept the most recently added.
181  if (http_listeners_.size() > 1) {
182  // Stop no longer used listeners.
183  for (auto l = http_listeners_.begin(); l != http_listeners_.end() - 1;
184  ++l) {
185  (*l)->stop();
186  }
187  // We have stopped listeners but there may be some pending handlers
188  // related to these listeners. Need to invoke these handlers.
189  getIoService()->get_io_service().poll();
190  // Finally, we're ready to remove no longer used listeners.
191  http_listeners_.erase(http_listeners_.begin(),
192  http_listeners_.end() - 1);
193  }
194 }
195 
196 
199  return (boost::dynamic_pointer_cast<CtrlAgentCfgMgr>(getCfgMgr()));
200 }
201 
204  // Return the most recent listener or null.
205  return (http_listeners_.empty() ? ConstHttpListenerPtr() :
206  http_listeners_.back());
207 }
208 
209 bool
211  // If there are is a listener, we're listening.
212  return (static_cast<bool>(getHttpListener()));
213 }
214 
215 } // namespace isc::agent
216 } // namespace isc
boost::shared_ptr< HttpResponseCreatorFactory > HttpResponseCreatorFactoryPtr
Pointer to the HttpResponseCreatorFactory.
bool isListening() const
Checks if the process is listening to the HTTP requests.
Definition: ca_process.cc:210
void setShutdownFlag(bool value)
Sets the process shut down flag to the given value.
Definition: d_process.h:152
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition: macros.h:20
ConstElementPtr createAnswer(const int status_code, const std::string &text, const ConstElementPtr &arg)
boost::shared_ptr< DCfgMgrBase > DCfgMgrBasePtr
Defines a shared pointer to DCfgMgrBase.
Definition: d_cfg_mgr.h:219
boost::shared_ptr< const HttpListener > ConstHttpListenerPtr
Pointer to the const HttpListener.
Definition: listener.h:140
static process::DControllerBasePtr & instance()
Static singleton instance method.
virtual isc::data::ConstElementPtr shutdown(isc::data::ConstElementPtr args)
Initiates the process's shutdown process.
Definition: ca_process.cc:97
boost::shared_ptr< CtrlAgentCfgMgr > CtrlAgentCfgMgrPtr
Defines a shared pointer to CtrlAgentCfgMgr.
Definition: ca_cfg_mgr.h:208
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
virtual void run()
Implements the process's event loop.
Definition: ca_process.cc:43
isc::log::Logger agent_logger("ctrl-agent")
Control Agent logger.
Definition: ca_log.h:18
HTTP response creator factory for Control Agent.
HTTP listener.
Definition: listener.h:51
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
DCfgMgrBasePtr & getCfgMgr()
Fetches the process's configuration manager.
Definition: d_process.h:181
Idle connection timeout.
Definition: listener.h:66
A generic exception that is thrown when an unexpected error condition occurs.
CtrlAgentCfgMgrPtr getCtrlAgentCfgMgr()
Returns a pointer to the configuration manager.
Definition: ca_process.cc:198
boost::shared_ptr< const Element > ConstElementPtr
Definition: data.h:23
constexpr long TIMEOUT_AGENT_RECEIVE_COMMAND
Timeout for the Control Agent to receive command over the RESTful interface.
Definition: timeouts.h:21
virtual isc::data::ConstElementPtr configure(isc::data::ConstElementPtr config_set, bool check_only=false)
Processes the given configuration.
Definition: ca_process.cc:103
void stopIOService()
Convenience method for stopping IOservice processing.
Definition: d_process.h:174
ConstElementPtr parseAnswer(int &rcode, const ConstElementPtr &msg)
Defines the logger used by the top-level component of kea-dhcp-ddns.
This file contains several functions and constants that are used for handling commands and responses ...
asiolink::IOServicePtr & getIoService()
Fetches the controller's IOService.
Definition: d_process.h:166
Ctrl Agent Configuration Manager.
Definition: ca_cfg_mgr.h:158
Exception thrown if the process encountered an operational error.
Definition: d_process.h:22
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:203
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition: macros.h:14
boost::shared_ptr< CtrlAgentController > CtrlAgentControllerPtr
Definition: ca_controller.h:80
Application Process Interface.
Definition: d_process.h:67
#define LOG_FATAL(LOGGER, MESSAGE)
Macro to conveniently test fatal output and log it.
Definition: macros.h:38
boost::shared_ptr< HttpListener > HttpListenerPtr
Pointer to the HttpListener.
Definition: listener.h:137
virtual void init()
Initialize the Control Agent process.
Definition: ca_process.cc:39
boost::shared_ptr< CtrlAgentCfgContext > CtrlAgentCfgContextPtr
Pointer to a configuration context.
Definition: ca_cfg_mgr.h:20
constexpr long TIMEOUT_AGENT_IDLE_CONNECTION_TIMEOUT
Timeout for the idle connection to be closed.
Definition: timeouts.h:24
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
bool shouldShutdown() const
Checks if the process has been instructed to shut down.
Definition: d_process.h:145
HTTP request timeout value.
Definition: listener.h:55
boost::shared_ptr< ConfigBase > ConfigPtr
Non-const pointer to the SrvConfig.
Definition: config_base.h:119