31#include <boost/make_shared.hpp>
32#include <boost/pointer_cast.hpp>
33#include <boost/weak_ptr.hpp>
45namespace ph = std::placeholders;
50class CommandUnsupportedError :
public CtrlChannelError {
52 CommandUnsupportedError(
const char* file,
size_t line,
const char* what) :
53 CtrlChannelError(file, line, what) {}
57class ConflictError :
public CtrlChannelError {
59 ConflictError(
const char* file,
size_t line,
const char* what) :
60 CtrlChannelError(file, line, what) {}
101 if (!
config_->getEnableMultiThreading()) {
107 config_->getHttpClientThreads(),
true));
110 if (
config_->getHttpDedicatedListener()) {
112 auto my_url =
config_->getThisServerConfig()->getUrl();
117 server_address =
IOAddress(my_url.getStrippedHostname());
118 }
catch (
const std::exception& ex) {
120 <<
" is not a valid IP address");
124 uint32_t listener_threads =
config_->getHttpListenerThreads();
127 auto tls_context =
config_->getThisServerConfig()->getTlsContext();
131 config_->getThisServerConfig()->getBasicAuthConfig();
134 std::unordered_set<std::string> command_accept_list;
135 if (
config_->getRestrictCommands()) {
149 command_accept_list));
154 .arg(
config_->getThisServerName())
167HAService::getCSCallbacksSetName()
const {
168 std::ostringstream s;
169 s <<
"HA_MT_" <<
id_;
206 std::bind(&HAService::backupStateHandler,
this),
210 std::bind(&HAService::communicationRecoveryStateHandler,
this),
214 std::bind(&HAService::normalStateHandler,
this),
218 std::bind(&HAService::normalStateHandler,
this),
222 std::bind(&HAService::inMaintenanceStateHandler,
this),
226 std::bind(&HAService::partnerDownStateHandler,
this),
230 std::bind(&HAService::partnerInMaintenanceStateHandler,
this),
234 std::bind(&HAService::passiveBackupStateHandler,
this),
238 std::bind(&HAService::readyStateHandler,
this),
242 std::bind(&HAService::syncingStateHandler,
this),
246 std::bind(&HAService::terminatedStateHandler,
this),
250 std::bind(&HAService::waitingStateHandler,
this),
254 std::bind(&HAService::downStateHandler,
this),
259HAService::backupStateHandler() {
277HAService::communicationRecoveryStateHandler() {
401HAService::normalStateHandler() {
465 }
else if (
config_->amAllowingCommRecovery()) {
485HAService::inMaintenanceStateHandler() {
499 .arg(
config_->getThisServerName());
511HAService::downStateHandler() {
554HAService::partnerDownStateHandler() {
568 if (maintenance ||
config_->getThisServerConfig()->isAutoFailover()) {
583 .arg(
config_->getThisServerName());
657HAService::partnerInMaintenanceStateHandler() {
670 .arg(
config_->getThisServerName());
709HAService::passiveBackupStateHandler() {
730HAService::readyStateHandler() {
814HAService::syncingStateHandler() {
879 unsigned int dhcp_disable_timeout =
880 static_cast<unsigned int>(
config_->getSyncTimeout() / 1000);
881 if (dhcp_disable_timeout == 0) {
882 ++dhcp_disable_timeout;
886 std::string status_message;
888 config_->getFailoverPeerConfig(),
889 dhcp_disable_timeout);
909HAService::terminatedStateHandler() {
925 .arg(
config_->getThisServerName());
932HAService::waitingStateHandler() {
1004 if (!partner_in_terminated.is_not_a_date_time() &&
1007 .arg(
config_->getThisServerName())
1020 .arg(
config_->getThisServerName());
1058 boost::to_upper(current_state_name);
1059 boost::to_upper(new_state_name);
1065 std::string partner_state_name =
getStateLabel(partner_state);
1066 boost::to_upper(partner_state_name);
1070 .arg(
config_->getThisServerName())
1071 .arg(current_state_name)
1072 .arg(new_state_name)
1073 .arg(partner_state_name);
1078 .arg(
config_->getThisServerName())
1079 .arg(current_state_name)
1080 .arg(new_state_name);
1089 .arg(
config_->getThisServerName());
1102 .arg(
config_->getThisServerName())
1103 .arg(new_state_name);
1105 }
else if (!
config_->amSendingLeaseUpdates()) {
1108 .arg(
config_->getThisServerName())
1109 .arg(new_state_name);
1116 .arg(
config_->getThisServerName())
1117 .arg(new_state_name);
1128 switch (
config_->getHAMode()) {
1142 .arg(
config_->getThisServerName());
1154 boost::to_upper(state_name);
1156 .arg(
config_->getThisServerName())
1173 return (inScopeInternal(query4));
1178 return (inScopeInternal(query6));
1181template<
typename QueryPtrType>
1183HAService::inScopeInternal(QueryPtrType& query) {
1185 std::string scope_class;
1203 return (shouldReclaimInternal(lease4));
1208 return (shouldReclaimInternal(lease6));
1211template<
typename LeasePtrType>
1213HAService::shouldReclaimInternal(
const LeasePtrType& lease)
const {
1220 boost::to_upper(current_state_name);
1233 boost::to_upper(current_state_name);
1235 .arg(
config_->getThisServerName())
1236 .arg(current_state_name);
1239 }
else if (should_enable && !
network_state_->isServiceEnabled()) {
1241 boost::to_upper(current_state_name);
1243 .arg(
config_->getThisServerName())
1244 .arg(current_state_name);
1282 if (!should_terminate) {
1289 return (should_terminate);
1311 .arg(
config_->getThisServerName());
1319 .arg(
config_->getThisServerName());
1327 .arg(
config_->getThisServerName());
1347 size_t sent_num = 0;
1350 for (
auto const& p : peers_configs) {
1358 for (
auto const& l : *deleted_leases) {
1369 for (
auto const& l : *leases) {
1391 for (
auto const& l : *deleted_leases) {
1404 for (
auto const& l : *leases) {
1425 leases->push_back(lease);
1440 size_t sent_num = 0;
1443 for (
auto const& p : peers_configs) {
1450 for (
auto const& l : *deleted_leases) {
1461 for (
auto const& l : *leases) {
1497template<
typename QueryPtrType>
1502 std::lock_guard<std::mutex> lock(mutex_);
1503 return (leaseUpdateCompleteInternal(query, parking_lot));
1505 return (leaseUpdateCompleteInternal(query, parking_lot));
1509template<
typename QueryPtrType>
1511HAService::leaseUpdateCompleteInternal(QueryPtrType& query,
1513 auto it = pending_requests_.find(query);
1517 if (it == pending_requests_.end() || (--pending_requests_[query] <= 0)) {
1519 parking_lot->unpark(query);
1524 if (it != pending_requests_.end()) {
1525 pending_requests_.erase(it);
1532template<
typename QueryPtrType>
1536 std::lock_guard<std::mutex> lock(mutex_);
1537 updatePendingRequestInternal(query);
1539 updatePendingRequestInternal(query);
1543template<
typename QueryPtrType>
1545HAService::updatePendingRequestInternal(QueryPtrType& query) {
1546 if (pending_requests_.count(query) == 0) {
1547 pending_requests_[query] = 1;
1549 ++pending_requests_[query];
1553template<
typename QueryPtrType>
1563 config->addBasicAuthHttpHeader(request);
1564 request->setBodyAsJson(command);
1565 request->finalize();
1574 boost::weak_ptr<typename QueryPtrType::element_type> weak_query(query);
1579 [
this, weak_query, parking_lot,
config]
1580 (
const boost::system::error_code& ec,
1582 const std::string& error_str) {
1586 QueryPtrType query_ptr = weak_query.lock();
1588 isc_throw(Unexpected,
"query is null while receiving response from"
1589 " HA peer. This is programmatic error");
1600 bool lease_update_success =
true;
1601 bool lease_update_conflict =
false;
1604 if (ec || !error_str.empty()) {
1605 LOG_WARN(ha_logger, HA_LEASE_UPDATE_COMMUNICATIONS_FAILED)
1606 .arg(config_->getThisServerName())
1607 .arg(query_ptr->getLabel())
1608 .arg(config->getLogLabel())
1609 .arg(ec ? ec.message() : error_str);
1613 lease_update_success = false;
1619 auto args = verifyAsyncResponse(http_response, rcode);
1622 logFailedLeaseUpdates(query_ptr, args);
1624 } catch (
const ConflictError& ex) {
1626 lease_update_conflict =
true;
1627 lease_update_success =
false;
1631 .arg(
config_->getThisServerName())
1632 .arg(query_ptr->getLabel())
1633 .arg(
config->getLogLabel())
1636 }
catch (
const std::exception& ex) {
1639 .arg(
config_->getThisServerName())
1640 .arg(query_ptr->getLabel())
1641 .arg(
config->getLogLabel())
1645 lease_update_success =
false;
1654 if (!lease_update_success) {
1657 if (!lease_update_conflict) {
1660 communication_state_->setPartnerUnavailable();
1665 communication_state_->reportSuccessfulLeaseUpdate(query_ptr);
1672 if (config_->amWaitingBackupAck() || (
config->getRole() != HAConfig::PeerConfig::BACKUP)) {
1676 if (!lease_update_success) {
1678 parking_lot->drop(query_ptr);
1687 if (leaseUpdateComplete(query_ptr, parking_lot)) {
1693 runModel(HA_LEASE_UPDATES_COMPLETE_EVT);
1697 std::bind(&HAService::clientConnectHandler,
this, ph::_1, ph::_2),
1698 std::bind(&HAService::clientHandshakeHandler,
this, ph::_1),
1699 std::bind(&HAService::clientCloseHandler,
this, ph::_1)
1706 if (config_->amWaitingBackupAck() || (
config->getRole() != HAConfig::PeerConfig::BACKUP)) {
1708 updatePendingRequest(query);
1715 if (!
config_->amSendingLeaseUpdates()) {
1749 if (!
config_->amSendingLeaseUpdates()) {
1770 auto log_proc = [query, args](
const std::string& param_name,
const log::MessageID& mesid) {
1772 auto failed_leases = args->get(param_name);
1775 if (failed_leases && (failed_leases->getType() ==
Element::list)) {
1777 for (
unsigned i = 0; i < failed_leases->size(); ++i) {
1778 auto lease = failed_leases->get(i);
1782 auto ip_address = lease->get(
"ip-address");
1785 auto lease_type = lease->get(
"type");
1788 auto error_message = lease->get(
"error-message");
1791 .arg(query->getLabel())
1793 lease_type->stringValue() :
"(unknown)")
1795 ip_address->stringValue() :
"(unknown)")
1797 error_message->stringValue() :
"(unknown)");
1817 role =
config_->getThisServerConfig()->getRole();
1828 std::set<std::string> scopes =
query_filter_.getServedScopes();
1830 for (
auto const& scope : scopes) {
1833 local->set(
"scopes", list);
1836 if (my_time.is_not_a_date_time()) {
1841 ha_servers->set(
"local", local);
1847 return (ha_servers);
1854 role =
config_->getFailoverPeerConfig()->getRole();
1862 ha_servers->set(
"remote", remote);
1864 return (ha_servers);
1878 for (
auto const& scope : scopes) {
1881 arguments->set(
"scopes", scopes_list);
1883 arguments->set(
"unsent-update-count",
1918 partner_config->addBasicAuthHttpHeader(request);
1921 request->finalize();
1928 client_->asyncSendRequest(partner_config->getUrl(),
1929 partner_config->getTlsContext(),
1931 [
this, partner_config, sync_complete_notified]
1932 (
const boost::system::error_code& ec,
1934 const std::string& error_str) {
1942 bool heartbeat_success = true;
1945 if (ec || !error_str.empty()) {
1946 LOG_WARN(ha_logger, HA_HEARTBEAT_COMMUNICATIONS_FAILED)
1947 .arg(config_->getThisServerName())
1948 .arg(partner_config->getLogLabel())
1949 .arg(ec ? ec.message() : error_str);
1950 heartbeat_success = false;
1959 ConstElementPtr args = verifyAsyncResponse(http_response, rcode);
1960 if (!args || args->getType() != Element::map) {
1961 isc_throw(CtrlChannelError,
"returned arguments in the response"
1965 ConstElementPtr state = args->get(
"state");
1966 if (!state || state->getType() != Element::string) {
1967 isc_throw(CtrlChannelError,
"server state not returned in response"
1968 " to a ha-heartbeat command or it is not a string");
1972 communication_state_->setPartnerState(state->stringValue());
1974 ConstElementPtr date_time = args->get(
"date-time");
1975 if (!date_time || date_time->getType() != Element::string) {
1976 isc_throw(CtrlChannelError,
"date-time not returned in response"
1977 " to a ha-heartbeat command or it is not a string");
1980 communication_state_->setPartnerTime(date_time->stringValue());
1984 auto scopes = args->get(
"scopes");
1985 communication_state_->setPartnerScopes(scopes);
2000 auto unsent_update_count = args->get(
"unsent-update-count");
2001 if (unsent_update_count) {
2002 if (unsent_update_count->getType() != Element::integer) {
2003 isc_throw(CtrlChannelError,
"unsent-update-count returned in"
2004 " the ha-heartbeat response is not an integer");
2006 communication_state_->setPartnerUnsentUpdateCount(static_cast<uint64_t>
2007 (unsent_update_count->intValue()));
2010 } catch (
const std::exception& ex) {
2012 .arg(
config_->getThisServerName())
2013 .arg(partner_config->getLogLabel())
2015 heartbeat_success =
false;
2021 if (heartbeat_success) {
2022 communication_state_->poke();
2027 communication_state_->setPartnerUnavailable();
2029 if (communication_state_->isCommunicationInterrupted()) {
2030 LOG_WARN(ha_logger, HA_COMMUNICATION_INTERRUPTED)
2031 .arg(config_->getThisServerName())
2032 .arg(partner_config->getName());
2040 if (sync_complete_notified && !heartbeat_success) {
2041 postNextEvent(HA_SYNCED_PARTNER_UNAVAILABLE_EVT);
2048 runModel(HA_HEARTBEAT_COMPLETE_EVT);
2051 std::bind(&HAService::clientConnectHandler,
this, ph::_1, ph::_2),
2052 std::bind(&HAService::clientHandshakeHandler,
this, ph::_1),
2053 std::bind(&HAService::clientCloseHandler,
this, ph::_1)
2066 if (
config_->getHeartbeatDelay() > 0) {
2076 const unsigned int max_period,
2083 remote_config->addBasicAuthHttpHeader(request);
2087 request->finalize();
2095 remote_config->getTlsContext(),
2097 [
this, remote_config, post_request_action]
2098 (
const boost::system::error_code& ec,
2100 const std::string& error_str) {
2109 std::string error_message;
2112 if (ec || !error_str.empty()) {
2113 error_message = (ec ? ec.message() : error_str);
2114 LOG_ERROR(ha_logger, HA_DHCP_DISABLE_COMMUNICATIONS_FAILED)
2115 .arg(config_->getThisServerName())
2116 .arg(remote_config->getLogLabel())
2117 .arg(error_message);
2123 static_cast<void>(verifyAsyncResponse(http_response, rcode));
2125 } catch (
const std::exception& ex) {
2126 error_message = ex.what();
2128 .arg(
config_->getThisServerName())
2129 .arg(remote_config->getLogLabel())
2130 .arg(error_message);
2136 if (!error_message.empty()) {
2137 communication_state_->setPartnerUnavailable();
2141 if (post_request_action) {
2142 post_request_action(error_message.empty(),
2148 std::bind(&HAService::clientConnectHandler,
this, ph::_1, ph::_2),
2149 std::bind(&HAService::clientHandshakeHandler,
this, ph::_1),
2150 std::bind(&HAService::clientCloseHandler,
this, ph::_1)
2162 remote_config->addBasicAuthHttpHeader(request);
2165 request->finalize();
2173 remote_config->getTlsContext(),
2175 [
this, remote_config, post_request_action]
2176 (
const boost::system::error_code& ec,
2178 const std::string& error_str) {
2187 std::string error_message;
2190 if (ec || !error_str.empty()) {
2191 error_message = (ec ? ec.message() : error_str);
2192 LOG_ERROR(ha_logger, HA_DHCP_ENABLE_COMMUNICATIONS_FAILED)
2193 .arg(config_->getThisServerName())
2194 .arg(remote_config->getLogLabel())
2195 .arg(error_message);
2201 static_cast<void>(verifyAsyncResponse(http_response, rcode));
2203 } catch (
const std::exception& ex) {
2204 error_message = ex.what();
2206 .arg(
config_->getThisServerName())
2207 .arg(remote_config->getLogLabel())
2208 .arg(error_message);
2214 if (!error_message.empty()) {
2215 communication_state_->setPartnerUnavailable();
2219 if (post_request_action) {
2220 post_request_action(error_message.empty(),
2226 std::bind(&HAService::clientConnectHandler,
this, ph::_1, ph::_2),
2227 std::bind(&HAService::clientHandshakeHandler,
this, ph::_1),
2228 std::bind(&HAService::clientCloseHandler,
this, ph::_1)
2247 unsigned int dhcp_disable_timeout =
2248 static_cast<unsigned int>(
config_->getSyncTimeout() / 1000);
2249 if (dhcp_disable_timeout == 0) {
2251 dhcp_disable_timeout = 1;
2256 dhcp_disable_timeout,
LeasePtr(), null_action);
2262 const unsigned int max_period,
2265 const bool dhcp_disabled) {
2272 [
this, &http_client, remote_config, max_period, last_lease,
2273 post_sync_action, dhcp_disabled]
2274 (
const bool success,
const std::string& error_message,
const int) {
2282 last_lease, post_sync_action,
true);
2285 post_sync_action(success, error_message, dhcp_disabled);
2293 const unsigned int max_period,
2296 const bool dhcp_disabled) {
2301 remote_config->addBasicAuthHttpHeader(request);
2304 boost::dynamic_pointer_cast<Lease4>(last_lease),
config_->getSyncPageLimit()));
2308 boost::dynamic_pointer_cast<Lease6>(last_lease),
config_->getSyncPageLimit()));
2310 request->finalize();
2318 remote_config->getTlsContext(),
2320 [
this, remote_config, post_sync_action, &http_client, max_period, dhcp_disabled]
2321 (
const boost::system::error_code& ec,
2323 const std::string& error_str) {
2327 LeasePtr last_lease_in_callback;
2335 std::string error_message;
2338 if (ec || !error_str.empty()) {
2339 error_message = (ec ? ec.message() : error_str);
2340 LOG_ERROR(ha_logger, HA_LEASES_SYNC_COMMUNICATIONS_FAILED)
2341 .arg(config_->getThisServerName())
2342 .arg(remote_config->getLogLabel())
2343 .arg(error_message);
2349 ConstElementPtr args = verifyAsyncResponse(http_response, rcode);
2352 if (args && (args->getType() != Element::map)) {
2353 isc_throw(CtrlChannelError,
2354 "arguments in the received response must be a map");
2357 ConstElementPtr leases = args->get(
"leases");
2358 if (!leases || (leases->getType() != Element::list)) {
2359 isc_throw(CtrlChannelError,
2360 "server response does not contain leases argument or this"
2361 " argument is not a list");
2365 auto const& leases_element = leases->listValue();
2367 LOG_INFO(ha_logger, HA_LEASES_SYNC_LEASE_PAGE_RECEIVED)
2368 .arg(config_->getThisServerName())
2369 .arg(leases_element.size())
2370 .arg(remote_config->getLogLabel());
2373 uint64_t applied_lease_count = 0;
2374 for (auto l = leases_element.begin(); l != leases_element.end(); ++l) {
2377 if (server_type_ == HAServerType::DHCPv4) {
2378 Lease4Ptr lease = Lease4::fromElement(*l);
2383 if ((leases_element.size() >= config_->getSyncPageLimit()) &&
2384 (l + 1 == leases_element.end())) {
2385 last_lease_in_callback = boost::dynamic_pointer_cast<Lease>(lease);
2388 if (!lease_sync_filter_.shouldSync(lease)) {
2393 Lease4Ptr existing_lease = LeaseMgrFactory::instance().getLease4(lease->addr_);
2394 if (!existing_lease) {
2396 LeaseMgrFactory::instance().addLease(lease);
2397 ++applied_lease_count;
2398 LeaseMgr::updateStatsOnAdd(lease);
2399 } else if (existing_lease->cltt_ < lease->cltt_) {
2405 Lease::syncCurrentExpirationTime(*existing_lease, *lease);
2406 LeaseMgrFactory::instance().updateLease4(lease);
2407 ++applied_lease_count;
2408 LeaseMgr::updateStatsOnUpdate(existing_lease, lease);
2410 LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_LEASE_SYNC_STALE_LEASE4_SKIP)
2411 .arg(config_->getThisServerName())
2412 .arg(lease->addr_.toText())
2413 .arg(lease->subnet_id_);
2417 Lease6Ptr lease = Lease6::fromElement(*l);
2422 if ((leases_element.size() >= config_->getSyncPageLimit()) &&
2423 (l + 1 == leases_element.end())) {
2424 last_lease_in_callback = boost::dynamic_pointer_cast<Lease>(lease);
2427 if (!lease_sync_filter_.shouldSync(lease)) {
2432 Lease6Ptr existing_lease = LeaseMgrFactory::instance().getLease6(lease->type_,
2434 if (!existing_lease) {
2436 LeaseMgrFactory::instance().addLease(lease);
2437 ++applied_lease_count;
2438 LeaseMgr::updateStatsOnAdd(lease);
2439 } else if (existing_lease->cltt_ < lease->cltt_) {
2445 Lease::syncCurrentExpirationTime(*existing_lease, *lease);
2446 LeaseMgrFactory::instance().updateLease6(lease);
2447 ++applied_lease_count;
2448 LeaseMgr::updateStatsOnUpdate(existing_lease, lease);
2450 LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_LEASE_SYNC_STALE_LEASE6_SKIP)
2451 .arg(config_->getThisServerName())
2452 .arg(lease->addr_.toText())
2453 .arg(lease->subnet_id_);
2457 } catch (const std::exception& ex) {
2458 LOG_WARN(ha_logger, HA_LEASE_SYNC_FAILED)
2459 .arg(config_->getThisServerName())
2465 LOG_INFO(ha_logger, HA_LEASES_SYNC_APPLIED_LEASES)
2466 .arg(config_->getThisServerName())
2467 .arg(applied_lease_count);
2469 } catch (
const std::exception& ex) {
2470 error_message = ex.what();
2472 .arg(
config_->getThisServerName())
2473 .arg(remote_config->getLogLabel())
2474 .arg(error_message);
2480 if (!error_message.empty()) {
2481 communication_state_->setPartnerUnavailable();
2483 }
else if (last_lease_in_callback) {
2486 asyncSyncLeases(http_client, remote_config, max_period, last_lease_in_callback,
2487 post_sync_action, dhcp_disabled);
2492 if (post_sync_action) {
2493 post_sync_action(error_message.empty(),
2499 std::bind(&HAService::clientConnectHandler,
this, ph::_1, ph::_2),
2500 std::bind(&HAService::clientHandshakeHandler,
this, ph::_1),
2501 std::bind(&HAService::clientCloseHandler,
this, ph::_1)
2508 const unsigned int max_period) {
2511 remote_config =
config_->getPeerConfig(server_name);
2512 }
catch (
const std::exception& ex) {
2516 if (remote_config->getName() ==
config_->getThisServerName()) {
2518 +
"' points to local server but should point to a partner"));
2520 std::string answer_message;
2521 int sync_status =
synchronize(answer_message, remote_config, max_period);
2528 const unsigned int max_period) {
2535 [&](
const bool success,
const std::string& error_message,
2536 const bool dhcp_disabled) {
2541 status_message = error_message;
2547 if (dhcp_disabled) {
2553 [&](
const bool success_complete_notify,
2554 const std::string& error_message_complete_notify,
2561 [&](
const bool success_enable_dhcp,
2562 const std::string& error_message_enable_dhcp,
2567 if (!success_enable_dhcp && status_message.empty()) {
2568 status_message = error_message_enable_dhcp;
2580 if (!success_complete_notify && status_message.empty()) {
2581 status_message = error_message_complete_notify;
2594 [&](
const bool success_enable_dhcp,
2595 const std::string& error_message_enable_dhcp,
2597 if (!success_enable_dhcp && status_message.empty()) {
2598 status_message = error_message_enable_dhcp;
2617 .arg(
config_->getThisServerName())
2618 .arg(remote_config->getLogLabel());
2632 io_service->stopAndPoll();
2636 if (!status_message.empty()) {
2640 .arg(
config_->getThisServerName())
2641 .arg(remote_config->getLogLabel())
2642 .arg(status_message);
2649 status_message =
"Lease database synchronization complete.";
2653 .arg(
config_->getThisServerName())
2654 .arg(remote_config->getLogLabel())
2687 config->addBasicAuthHttpHeader(request);
2688 request->setBodyAsJson(command);
2689 request->finalize();
2697 [
this, &http_client,
config, post_request_action]
2698 (
const boost::system::error_code& ec,
2700 const std::string& error_str) {
2703 std::string error_message;
2705 if (ec || !error_str.empty()) {
2706 error_message = (ec ? ec.message() : error_str);
2707 LOG_WARN(ha_logger, HA_LEASES_BACKLOG_COMMUNICATIONS_FAILED)
2708 .arg(config_->getThisServerName())
2709 .arg(config->getLogLabel())
2710 .arg(ec ? ec.message() : error_str);
2715 auto args = verifyAsyncResponse(http_response, rcode);
2716 } catch (
const std::exception& ex) {
2717 error_message = ex.what();
2719 .arg(
config_->getThisServerName())
2720 .arg(
config->getLogLabel())
2730 if (error_message.empty()) {
2731 asyncSendLeaseUpdatesFromBacklog(http_client, config, post_request_action);
2733 post_request_action(error_message.empty(), error_message, rcode);
2741 if (num_updates == 0) {
2743 .arg(
config_->getThisServerName());
2749 auto remote_config =
config_->getFailoverPeerConfig();
2750 bool updates_successful =
true;
2753 .arg(
config_->getThisServerName())
2755 .arg(remote_config->getName());
2758 [&](
const bool success,
const std::string&,
const int) {
2760 updates_successful = success;
2774 io_service->stopAndPoll();
2776 if (updates_successful) {
2778 .arg(
config_->getThisServerName())
2779 .arg(remote_config->getName())
2780 .arg(stopwatch.logFormatLastDuration());
2783 return (updates_successful);
2797 config->addBasicAuthHttpHeader(request);
2798 request->setBodyAsJson(command);
2799 request->finalize();
2807 [
this,
config, post_request_action]
2808 (
const boost::system::error_code& ec,
2810 const std::string& error_str) {
2813 std::string error_message;
2815 if (ec || !error_str.empty()) {
2816 error_message = (ec ? ec.message() : error_str);
2817 LOG_WARN(ha_logger, HA_RESET_COMMUNICATIONS_FAILED)
2818 .arg(config_->getThisServerName())
2819 .arg(config->getLogLabel())
2820 .arg(ec ? ec.message() : error_str);
2825 auto args = verifyAsyncResponse(http_response, rcode);
2826 } catch (
const std::exception& ex) {
2827 error_message = ex.what();
2829 .arg(
config_->getThisServerName())
2830 .arg(
config->getLogLabel())
2835 post_request_action(error_message.empty(), error_message, rcode);
2843 auto remote_config =
config_->getFailoverPeerConfig();
2844 bool reset_successful =
true;
2847 [&](
const bool success,
const std::string&,
const int) {
2849 reset_successful = success;
2857 io_service->stopAndPoll();
2859 return (reset_successful);
2868 }
catch (
const std::exception& ex) {
2888 " maintenance for the server not in the"
2889 " in-maintenance state."));
2927 "Unable to transition the server from the "
2929 " in-maintenance state."));
2947 " partner-in-maintenance state."));
2959 remote_config->addBasicAuthHttpHeader(request);
2962 request->finalize();
2971 boost::system::error_code captured_ec;
2972 std::string captured_error_message;
2973 int captured_rcode = 0;
2977 remote_config->getTlsContext(),
2979 [
this, remote_config, &io_service, &captured_ec, &captured_error_message,
2981 (
const boost::system::error_code& ec,
2983 const std::string& error_str) {
2993 std::string error_message;
2996 if (ec || !error_str.empty()) {
2997 error_message = (ec ? ec.message() : error_str);
2998 LOG_ERROR(ha_logger, HA_MAINTENANCE_NOTIFY_COMMUNICATIONS_FAILED)
2999 .arg(config_->getThisServerName())
3000 .arg(remote_config->getLogLabel())
3001 .arg(error_message);
3007 static_cast<void>(verifyAsyncResponse(http_response, captured_rcode));
3009 } catch (
const std::exception& ex) {
3010 error_message = ex.what();
3012 .arg(
config_->getThisServerName())
3013 .arg(remote_config->getLogLabel())
3014 .arg(error_message);
3020 if (!error_message.empty()) {
3021 communication_state_->setPartnerUnavailable();
3025 captured_error_message = error_message;
3028 std::bind(&HAService::clientConnectHandler,
this, ph::_1, ph::_2),
3029 std::bind(&HAService::clientHandshakeHandler,
this, ph::_1),
3030 std::bind(&HAService::clientCloseHandler,
this, ph::_1)
3039 io_service->stopAndPoll();
3044 postNextEvent(HA_MAINTENANCE_START_EVT);
3045 verboseTransition(HA_PARTNER_DOWN_ST);
3048 "Server is now in the partner-down state as its"
3049 " partner appears to be offline for maintenance."));
3055 postNextEvent(HA_MAINTENANCE_START_EVT);
3056 verboseTransition(HA_PARTNER_IN_MAINTENANCE_ST);
3063 " partner-in-maintenance state. The partner server responded"
3064 " with the following message to the ha-maintenance-notify"
3065 " command: " + captured_error_message +
"."));
3070 "Server is now in the partner-in-maintenance state"
3071 " and its partner is in-maintenance state. The partner"
3072 " can be now safely shut down."));
3079 " request because the server is not in the"
3080 " partner-in-maintenance state."));
3094 remote_config->addBasicAuthHttpHeader(request);
3099 request->finalize();
3108 std::string error_message;
3112 remote_config->getTlsContext(),
3114 [
this, remote_config, &io_service, &error_message]
3115 (
const boost::system::error_code& ec,
3117 const std::string& error_str) {
3122 if (ec || !error_str.empty()) {
3123 error_message = (ec ? ec.message() : error_str);
3124 LOG_ERROR(ha_logger, HA_MAINTENANCE_NOTIFY_CANCEL_COMMUNICATIONS_FAILED)
3125 .arg(config_->getThisServerName())
3126 .arg(remote_config->getLogLabel())
3127 .arg(error_message);
3134 ConstElementPtr args = verifyAsyncResponse(http_response, rcode);
3139 communication_state_->setPartnerUnavailable();
3143 if (args && args->getType() == Element::map) {
3145 ConstElementPtr state = args->get(
"state");
3147 if (state->getType() != Element::string) {
3148 isc_throw(CtrlChannelError,
"server state not returned in response"
3149 " to a ha-heartbeat command or it is not a string");
3151 communication_state_->setPartnerState(state->stringValue());
3154 } catch (
const std::exception& ex) {
3155 error_message = ex.what();
3157 .arg(
config_->getThisServerName())
3158 .arg(remote_config->getLogLabel())
3159 .arg(error_message);
3165 if (!error_message.empty()) {
3166 communication_state_->setPartnerUnavailable();
3170 std::bind(&HAService::clientConnectHandler,
this, ph::_1, ph::_2),
3171 std::bind(&HAService::clientHandshakeHandler,
this, ph::_1),
3172 std::bind(&HAService::clientCloseHandler,
this, ph::_1)
3181 io_service->stopAndPoll();
3185 if (!error_message.empty()) {
3187 "Unable to cancel maintenance. The partner server responded"
3188 " with the following message to the ha-maintenance-notify"
3189 " command: " + error_message +
"."));
3195 postNextEvent(HA_MAINTENANCE_CANCEL_EVT);
3196 verboseTransition(next_state);
3200 "Server maintenance successfully canceled."));
3212 remote_config->addBasicAuthHttpHeader(request);
3216 request->finalize();
3224 remote_config->getTlsContext(),
3226 [
this, remote_config, post_request_action]
3227 (
const boost::system::error_code& ec,
3229 const std::string& error_str) {
3238 std::string error_message;
3241 if (ec || !error_str.empty()) {
3242 error_message = (ec ? ec.message() : error_str);
3243 LOG_ERROR(ha_logger, HA_SYNC_COMPLETE_NOTIFY_COMMUNICATIONS_FAILED)
3244 .arg(config_->getThisServerName())
3245 .arg(remote_config->getLogLabel())
3246 .arg(error_message);
3252 static_cast<void>(verifyAsyncResponse(http_response, rcode));
3254 } catch (
const CommandUnsupportedError& ex) {
3257 }
catch (
const std::exception& ex) {
3258 error_message = ex.what();
3260 .arg(
config_->getThisServerName())
3261 .arg(remote_config->getLogLabel())
3262 .arg(error_message);
3268 if (!error_message.empty()) {
3269 communication_state_->setPartnerUnavailable();
3273 if (post_request_action) {
3274 post_request_action(error_message.empty(),
3280 std::bind(&HAService::clientConnectHandler,
this, ph::_1, ph::_2),
3281 std::bind(&HAService::clientHandshakeHandler,
this, ph::_1),
3282 std::bind(&HAService::clientCloseHandler,
this, ph::_1)
3304 "Server successfully notified about the synchronization completion."));
3313 boost::dynamic_pointer_cast<HttpResponseJson>(response);
3314 if (!json_response) {
3343 if (body->empty()) {
3354 std::ostringstream s;
3363 s << args->stringValue() <<
" (";
3366 s <<
"error code " << rcode <<
")";
3371 isc_throw(CommandUnsupportedError, s.str());
3379 auto failed_leases = args->get(
"failed-leases");
3380 if (!failed_leases || (failed_leases->getType() !=
Element::list)) {
3384 auto conflict =
false;
3386 for (
unsigned i = 0; i < failed_leases->size(); ++i) {
3387 auto lease = failed_leases->get(i);
3391 auto result = lease->get(
"result");
3395 auto error_message = lease->get(
"error-message");
3398 if (error_message && error_message->getType()) {
3399 s << error_message->stringValue() <<
" (";
3401 s <<
"error code " << result->intValue() <<
")";
3409 conflict_error_message = error_message;
3415 if (conflict_error_message &&
3417 s << conflict_error_message->stringValue() <<
" (";
3435 if (
client_->getThreadIOService()) {
3443 if ((!ec || (ec.value() == boost::asio::error::in_progress))
3444 && (tcp_native_fd >= 0)) {
3467 client_->closeIfOutOfBand(tcp_native_fd);
3472 if ((tcp_native_fd >= 0) &&
3481 std::lock_guard<std::mutex> lock(mutex_);
3482 return (pending_requests_.size());
3484 return (pending_requests_.size());
3488template<
typename QueryPtrType>
3492 std::lock_guard<std::mutex> lock(mutex_);
3493 return (getPendingRequestInternal(query));
3495 return (getPendingRequestInternal(query));
3499template<
typename QueryPtrType>
3501HAService::getPendingRequestInternal(
const QueryPtrType& query) {
3502 if (pending_requests_.count(query) == 0) {
3505 return (pending_requests_[query]);
3526 .arg(
config_->getThisServerName())
3531 }
catch (
const std::exception& ex) {
3533 .arg(
config_->getThisServerName())
3567 }
catch (
const std::exception& ex) {
3569 .arg(
config_->getThisServerName())
3586 }
catch (std::exception& ex) {
3588 .arg(
config_->getThisServerName())
static ElementPtr create(const Position &pos=ZERO_POSITION())
Create a NullElement.
static ElementPtr createMap(const Position &pos=ZERO_POSITION())
Creates an empty MapElement type ElementPtr.
static ElementPtr createList(const Position &pos=ZERO_POSITION())
Creates an empty ListElement type ElementPtr.
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
Exception thrown when a worker thread is trying to stop or pause the respective thread pool (which wo...
A generic exception that is thrown when an unexpected error condition occurs.
The IOAddress class represents an IP addresses (version agnostic).
static const IOAddress & IPV4_ZERO_ADDRESS()
Returns an address set to all zeros.
The IOService class is a wrapper for the ASIO io_context class.
A multi-threaded HTTP listener that can process API commands requests.
A standard control channel exception that is thrown if a function is there is a problem with one of t...
void deleteExternalSocket(int socketfd)
Deletes external socket.
static IfaceMgr & instance()
IfaceMgr is a singleton class.
void addExternalSocket(int socketfd, SocketCallback callback)
Adds external socket and a callback.
static data::ConstElementPtr createLease4Delete(const dhcp::Lease4 &lease4)
Creates lease4-del command.
static data::ConstElementPtr createHeartbeat(const std::string &server_name, const HAServerType &server_type)
Creates ha-heartbeat command for DHCP server.
static std::unordered_set< std::string > ha_commands4_
List of commands used by the High Availability in v4.
static data::ConstElementPtr createLease4Update(const dhcp::Lease4 &lease4)
Creates lease4-update command.
static data::ConstElementPtr createSyncCompleteNotify(const unsigned int origin_id, const std::string &server_name, const HAServerType &server_type)
Creates ha-sync-complete-notify command.
static data::ConstElementPtr createLease6BulkApply(const dhcp::Lease6CollectionPtr &leases, const dhcp::Lease6CollectionPtr &deleted_leases)
Creates lease6-bulk-apply command.
static data::ConstElementPtr createLease6GetPage(const dhcp::Lease6Ptr &lease6, const uint32_t limit)
Creates lease6-get-page command.
static data::ConstElementPtr createDHCPDisable(const unsigned int origin_id, const unsigned int max_period, const HAServerType &server_type)
Creates dhcp-disable command for DHCP server.
static data::ConstElementPtr createDHCPEnable(const unsigned int origin_id, const HAServerType &server_type)
Creates dhcp-enable command for DHCP server.
static data::ConstElementPtr createMaintenanceNotify(const std::string &server_name, const bool cancel, const int state, const HAServerType &server_type)
Creates ha-maintenance-notify command.
static std::unordered_set< std::string > ha_commands6_
List of commands used by the High Availability in v6.
static data::ConstElementPtr createHAReset(const std::string &server_name, const HAServerType &server_type)
Creates ha-reset command.
static data::ConstElementPtr createLease4GetPage(const dhcp::Lease4Ptr &lease4, const uint32_t limit)
Creates lease4-get-page command.
Holds communication state between DHCPv4 servers.
Holds communication state between DHCPv6 servers.
static std::string roleToString(const HAConfig::PeerConfig::Role &role)
Returns role name.
Role
Server's role in the High Availability setup.
std::map< std::string, PeerConfigPtr > PeerConfigMap
Map of the servers' configurations.
static std::string HAModeToString(const HAMode &ha_mode)
Returns HA mode name.
boost::shared_ptr< PeerConfig > PeerConfigPtr
Pointer to the server's configuration.
static const int HA_MAINTENANCE_START_EVT
ha-maintenance-start command received.
bool inScope(dhcp::Pkt4Ptr &query4)
Checks if the DHCPv4 query should be processed by this server.
void adjustNetworkState()
Enables or disables network state depending on the served scopes.
void stopClientAndListener()
Stop the client and(or) listener instances.
int getNormalState() const
Returns normal operation state for the current configuration.
bool shouldQueueLeaseUpdates(const HAConfig::PeerConfigPtr &peer_config) const
Checks if the lease updates should be queued.
static const int HA_HEARTBEAT_COMPLETE_EVT
Finished heartbeat command.
void asyncSendHAReset(http::HttpClient &http_client, const HAConfig::PeerConfigPtr &remote_config, PostRequestCallback post_request_action)
Sends ha-reset command to partner asynchronously.
bool clientConnectHandler(const boost::system::error_code &ec, int tcp_native_fd)
HttpClient connect callback handler.
void asyncSyncLeases()
Asynchronously reads leases from a peer and updates local lease database.
bool isMaintenanceCanceled() const
Convenience method checking if the current state is a result of canceling the maintenance.
data::ConstElementPtr processMaintenanceCancel()
Processes ha-maintenance-cancel command and returns a response.
void checkPermissionsClientAndListener()
Check client and(or) listener current thread permissions to perform thread pool state transition.
bool shouldReclaim(const dhcp::Lease4Ptr &lease4) const
Checks if the lease should be reclaimed by this server.
void asyncSendLeaseUpdate(const QueryPtrType &query, const HAConfig::PeerConfigPtr &config, const data::ConstElementPtr &command, const hooks::ParkingLotHandlePtr &parking_lot)
Asynchronously sends lease update to the peer.
void verboseTransition(const unsigned state)
Transitions to a desired state and logs it.
bool sendLeaseUpdatesFromBacklog()
Attempts to send all lease updates from the backlog synchronously.
config::CmdHttpListenerPtr listener_
HTTP listener instance used to receive and respond to HA commands and lease updates.
void clientCloseHandler(int tcp_native_fd)
HttpClient close callback handler.
bool leaseUpdateComplete(QueryPtrType &query, const hooks::ParkingLotHandlePtr &parking_lot)
Handle last pending request for this query.
HAConfigPtr config_
Pointer to the HA hooks library configuration.
data::ConstElementPtr processMaintenanceStart()
Processes ha-maintenance-start command and returns a response.
unsigned int id_
Unique service id.
HAServerType server_type_
DHCP server type.
bool sync_complete_notified_
An indicator that a partner sent ha-sync-complete-notify command.
bool shouldTerminate() const
Indicates if the server should transition to the terminated state.
data::ConstElementPtr processScopes(const std::vector< std::string > &scopes)
Processes ha-scopes command and returns a response.
dhcp::NetworkStatePtr network_state_
Pointer to the state of the DHCP service (enabled/disabled).
data::ConstElementPtr processSynchronize(const std::string &server_name, const unsigned int max_period)
Processes ha-sync command and returns a response.
void scheduleHeartbeat()
Schedules asynchronous heartbeat to a peer if it is not scheduled.
void asyncSyncCompleteNotify(http::HttpClient &http_client, const HAConfig::PeerConfigPtr &remote_config, PostRequestCallback post_request_action)
Schedules asynchronous "ha-sync-complete-notify" command to the specified server.
QueryFilter query_filter_
Selects queries to be processed/dropped.
static const int HA_MAINTENANCE_NOTIFY_EVT
ha-maintenance-notify command received.
static const int HA_SYNCED_PARTNER_UNAVAILABLE_EVT
The heartbeat command failed after receiving ha-sync-complete-notify command from the partner.
data::ConstElementPtr processMaintenanceNotify(const bool cancel, const std::string &state)
Processes ha-maintenance-notify command and returns a response.
void conditionalLogPausedState() const
Logs if the server is paused in the current state.
bool unpause()
Unpauses the HA state machine with logging.
static const int HA_CONTROL_RESULT_MAINTENANCE_NOT_ALLOWED
Control result returned in response to ha-maintenance-notify.
void serveDefaultScopes()
Instructs the HA service to serve default scopes.
size_t asyncSendLeaseUpdates(const dhcp::Pkt4Ptr &query, const dhcp::Lease4CollectionPtr &leases, const dhcp::Lease4CollectionPtr &deleted_leases, const hooks::ParkingLotHandlePtr &parking_lot)
Schedules asynchronous IPv4 leases updates.
bool isDHCPServiceDisabled() const
Convenience method checking if the dhcp state has been disabled by user of by database connection.
size_t pendingRequestSize()
Get the number of entries in the pending request map.
static const int HA_SYNCING_SUCCEEDED_EVT
Lease database synchronization succeeded.
bool sendHAReset()
Sends ha-reset command to partner synchronously.
std::function< void(const bool, const std::string &, const int)> PostRequestCallback
Callback invoked when request was sent and a response received or an error occurred.
asiolink::IOServicePtr io_service_
Pointer to the IO service object shared between this hooks library and the DHCP server.
void localDisableDHCPService()
Disables local DHCP service.
CommunicationStatePtr communication_state_
Holds communication state with a peer.
void logFailedLeaseUpdates(const dhcp::PktPtr &query, const data::ConstElementPtr &args) const
Log failed lease updates.
LeaseUpdateBacklog lease_update_backlog_
Backlog of DHCP lease updates.
virtual ~HAService()
Destructor.
static const int HA_SYNCING_FAILED_EVT
Lease database synchronization failed.
static const int HA_MAINTENANCE_CANCEL_EVT
ha-maintenance-cancel command received.
void asyncSendLeaseUpdatesFromBacklog(http::HttpClient &http_client, const HAConfig::PeerConfigPtr &remote_config, PostRequestCallback post_request_action)
Sends lease updates from backlog to partner asynchronously.
data::ConstElementPtr processHeartbeat()
Processes ha-heartbeat command and returns a response.
void asyncSyncLeasesInternal(http::HttpClient &http_client, const HAConfig::PeerConfigPtr &remote_config, const unsigned int max_period, const dhcp::LeasePtr &last_lease, PostSyncCallback post_sync_action, const bool dhcp_disabled)
Implements fetching one page of leases during synchronization.
data::ConstElementPtr processHAReset()
Processes ha-reset command and returns a response.
size_t asyncSendSingleLeaseUpdate(const dhcp::Pkt4Ptr &query, const dhcp::Lease4Ptr &lease, const hooks::ParkingLotHandlePtr &parking_lot)
Schedules an asynchronous IPv4 lease update.
void asyncSendHeartbeat()
Starts asynchronous heartbeat to a peer.
bool isPartnerStateInvalid() const
Indicates if the partner's state is invalid.
void startClientAndListener()
Start the client and(or) listener instances.
data::ConstElementPtr verifyAsyncResponse(const http::HttpResponsePtr &response, int &rcode)
Checks if the response is valid or contains an error.
void resumeClientAndListener()
Resumes client and(or) listener thread pool operations.
data::ConstElementPtr processStatusGet() const
Processes status-get command and returns a response.
int getPendingRequest(const QueryPtrType &query)
Get the number of scheduled requests for a given query.
LeaseSyncFilter lease_sync_filter_
Lease synchronization filter used in hub-and-spoke model.
int synchronize(std::string &status_message, const HAConfig::PeerConfigPtr &remote_config, const unsigned int max_period)
Synchronizes lease database with a partner.
bool shouldSendLeaseUpdates(const HAConfig::PeerConfigPtr &peer_config) const
Checks if the lease updates should be sent as result of leases allocation or release.
void serveFailoverScopes()
Instructs the HA service to serve failover scopes.
void localEnableDHCPService()
Enables local DHCP service.
static const int HA_LEASE_UPDATES_COMPLETE_EVT
Finished lease updates commands.
HAService(const unsigned int id, const asiolink::IOServicePtr &io_service, const dhcp::NetworkStatePtr &network_state, const HAConfigPtr &config, const HAServerType &server_type=HAServerType::DHCPv4)
Constructor.
void socketReadyHandler(int tcp_native_fd)
IfaceMgr external socket ready callback handler.
http::HttpClientPtr client_
HTTP client instance used to send HA commands and lease updates.
void updatePendingRequest(QueryPtrType &query)
Update pending request counter for this query.
bool shouldPartnerDown() const
Indicates if the server should transition to the partner down state.
void startHeartbeat()
Unconditionally starts one heartbeat to a peer.
data::ConstElementPtr processSyncCompleteNotify(const unsigned int origin_id)
Process ha-sync-complete-notify command and returns a response.
data::ConstElementPtr processContinue()
Processes ha-continue command and returns a response.
void asyncDisableDHCPService(http::HttpClient &http_client, const HAConfig::PeerConfigPtr &remote_config, const unsigned int max_period, PostRequestCallback post_request_action)
Schedules asynchronous "dhcp-disable" command to the specified server.
void pauseClientAndListener()
Pauses client and(or) listener thread pool operations.
std::function< void(const bool, const std::string &, const bool)> PostSyncCallback
Callback invoked when lease database synchronization is complete.
static const int HA_WAITING_TO_TERMINATED_ST_DELAY_MINUTES
A delay in minutes to transition from the waiting to terminated state when the partner remains in ter...
void asyncEnableDHCPService(http::HttpClient &http_client, const HAConfig::PeerConfigPtr &remote_config, PostRequestCallback post_request_action)
Schedules asynchronous "dhcp-enable" command to the specified server.
OpType
Type of the lease update (operation type).
bool inScope(const dhcp::Pkt4Ptr &query4, std::string &scope_class) const
Checks if this server should process the DHCPv4 query.
void stop()
Halts client-side IO activity.
void asyncSendRequest(const Url &url, const asiolink::TlsContextPtr &tls_context, const HttpRequestPtr &request, const HttpResponsePtr &response, const RequestHandler &request_callback, const RequestTimeout &request_timeout=RequestTimeout(10000), const ConnectHandler &connect_callback=ConnectHandler(), const HandshakeHandler &handshake_callback=HandshakeHandler(), const CloseHandler &close_callback=CloseHandler())
Queues new asynchronous HTTP request for a given URL.
This class parses and generates time values used in HTTP.
std::string rfc1123Format() const
Returns time value formatted as specified in RFC 1123.
static MultiThreadingMgr & instance()
Returns a single instance of Multi Threading Manager.
void removeCriticalSectionCallbacks(const std::string &name)
Removes the set of callbacks associated with a given name from the list of CriticalSection callbacks.
void addCriticalSectionCallbacks(const std::string &name, const CSCallbackSet::Callback &check_cb, const CSCallbackSet::Callback &entry_cb, const CSCallbackSet::Callback &exit_cb)
Adds a set of callbacks to the list of CriticalSection callbacks.
std::string getStateLabel(const int state) const
Fetches the label associated with an state value.
void unpauseModel()
Unpauses state model.
int getLastEvent() const
Fetches the model's last event.
bool isModelPaused() const
Returns whether or not the model is paused.
virtual void defineEvents()
Populates the set of events.
bool doOnExit()
Checks if on exit flag is true.
void defineEvent(int value, const std::string &label)
Adds an event value and associated label to the set of events.
virtual void verifyEvents()
Validates the contents of the set of events.
bool doOnEntry()
Checks if on entry flag is true.
static const int NOP_EVT
Signifies that no event has occurred.
int getCurrState() const
Fetches the model's current state.
void defineState(int value, const std::string &label, StateHandler handler, const StatePausing &state_pausing=STATE_PAUSE_NEVER)
Adds an state value and associated label to the set of states.
void startModel(const int start_state)
Begins execution of the model.
const EventPtr & getEvent(int value)
Fetches the event referred to by value.
virtual void defineStates()
Populates the set of states.
virtual void runModel(int event)
Processes events through the state model.
void transition(int state, int event)
Sets up the model to transition into given state with a given event.
int getNextEvent() const
Fetches the model's next event.
int getPrevState() const
Fetches the model's previous state.
const StatePtr getState(int value)
Fetches the state referred to by value.
void postNextEvent(int event)
Sets the next event to the given event value.
Utility class to measure code execution times.
void stop()
Stops the stopwatch.
std::string logFormatLastDuration() const
Returns the last measured duration in the format directly usable in log messages.
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.
An abstract API for lease database.
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
#define LOG_WARN(LOGGER, MESSAGE)
Macro to conveniently test warn output and log it.
boost::shared_ptr< IOService > IOServicePtr
Defines a smart pointer to an IOService instance.
const int CONTROL_RESULT_EMPTY
Status code indicating that the specified command was completed correctly, but failed to produce any ...
const char * CONTROL_TEXT
String used for storing textual description ("text").
ConstElementPtr parseAnswer(int &rcode, const ConstElementPtr &msg)
Parses a standard config/command level answer and returns arguments or text status code.
constexpr long TIMEOUT_DEFAULT_HTTP_CLIENT_REQUEST
Timeout for the HTTP clients awaiting a response to a request.
const int CONTROL_RESULT_ERROR
Status code indicating a general failure.
ConstElementPtr createAnswer()
Creates a standard config/command level success answer message (i.e.
const int CONTROL_RESULT_CONFLICT
Status code indicating that the command was unsuccessful due to a conflict between the command argume...
const int CONTROL_RESULT_COMMAND_UNSUPPORTED
Status code indicating that the specified command is not supported.
const char * CONTROL_RESULT
String used for result, i.e. integer status ("result").
const int CONTROL_RESULT_SUCCESS
Status code indicating a successful operation.
boost::shared_ptr< const Element > ConstElementPtr
boost::shared_ptr< Element > ElementPtr
boost::shared_ptr< isc::dhcp::Pkt > PktPtr
A pointer to either Pkt4 or Pkt6 packet.
std::string ClientClass
Defines a single class name.
boost::shared_ptr< Lease4Collection > Lease4CollectionPtr
A shared pointer to the collection of IPv4 leases.
boost::shared_ptr< Pkt4 > Pkt4Ptr
A pointer to Pkt4 object.
boost::shared_ptr< Lease6 > Lease6Ptr
Pointer to a Lease6 structure.
boost::shared_ptr< Lease > LeasePtr
Pointer to the lease object.
boost::shared_ptr< NetworkState > NetworkStatePtr
Pointer to the NetworkState object.
boost::shared_ptr< Lease6Collection > Lease6CollectionPtr
A shared pointer to the collection of IPv6 leases.
boost::shared_ptr< Pkt6 > Pkt6Ptr
A pointer to Pkt6 packet.
std::vector< Lease4Ptr > Lease4Collection
A collection of IPv4 leases.
boost::shared_ptr< Lease4 > Lease4Ptr
Pointer to a Lease4 structure.
const isc::log::MessageID HA_INVALID_PARTNER_STATE_LOAD_BALANCING
const isc::log::MessageID HA_RESUME_CLIENT_LISTENER_FAILED
const isc::log::MessageID HA_LOCAL_DHCP_ENABLE
const isc::log::MessageID HA_LEASES_BACKLOG_NOTHING_TO_SEND
const isc::log::MessageID HA_LEASES_BACKLOG_FAILED
const isc::log::MessageID HA_SYNC_FAILED
const isc::log::MessageID HA_TERMINATED_RESTART_PARTNER
const int HA_PASSIVE_BACKUP_ST
In passive-backup state with a single active server and backup servers.
const int HA_HOT_STANDBY_ST
Hot standby state.
const isc::log::MessageID HA_INVALID_PARTNER_STATE_COMMUNICATION_RECOVERY
const isc::log::MessageID HA_LEASES_BACKLOG_SUCCESS
const int HA_COMMUNICATION_RECOVERY_ST
Communication recovery state.
const isc::log::MessageID HA_STATE_MACHINE_CONTINUED
isc::log::Logger ha_logger("ha-hooks")
const isc::log::MessageID HA_LEASES_SYNC_FAILED
const isc::log::MessageID HA_SYNC_SUCCESSFUL
const int HA_UNAVAILABLE_ST
Special state indicating that this server is unable to communicate with the partner.
const isc::log::MessageID HA_CONFIG_LEASE_UPDATES_DISABLED_REMINDER
const isc::log::MessageID HA_SERVICE_STARTED
const int HA_TERMINATED_ST
HA service terminated state.
const int HA_IN_MAINTENANCE_ST
In maintenance state.
const int HA_LOAD_BALANCING_ST
Load balancing state.
const isc::log::MessageID HA_DHCP_ENABLE_FAILED
const int HA_DOWN_ST
Server down state, i.e. lost connection to lease storage database.
const isc::log::MessageID HA_LEASE_UPDATE_DELETE_FAILED_ON_PEER
const isc::log::MessageID HA_LEASES_BACKLOG_START
const isc::log::MessageID HA_SYNC_START
const isc::log::MessageID HA_HEARTBEAT_FAILED
const int HA_PARTNER_DOWN_ST
Partner down state.
const isc::log::MessageID HA_LEASE_UPDATES_ENABLED
const isc::log::MessageID HA_INVALID_PARTNER_STATE_HOT_STANDBY
const isc::log::MessageID HA_STATE_MACHINE_PAUSED
const isc::log::MessageID HA_TERMINATED
const isc::log::MessageID HA_DHCP_DISABLE_FAILED
boost::shared_ptr< HAConfig > HAConfigPtr
Pointer to the High Availability configuration structure.
const isc::log::MessageID HA_MAINTENANCE_STARTED_IN_PARTNER_DOWN
const int HA_PARTNER_IN_MAINTENANCE_ST
Partner in-maintenance state.
const isc::log::MessageID HA_MAINTENANCE_NOTIFY_FAILED
const int HA_WAITING_ST
Server waiting state, i.e. waiting for another server to be ready.
HAServerType
Lists possible server types for which HA service is created.
const int HA_BACKUP_ST
Backup state.
const isc::log::MessageID HA_PAUSE_CLIENT_LISTENER_ILLEGAL
const isc::log::MessageID HA_PAUSE_CLIENT_LISTENER_FAILED
const isc::log::MessageID HA_MAINTENANCE_SHUTDOWN_SAFE
const isc::log::MessageID HA_MAINTENANCE_NOTIFY_CANCEL_FAILED
const isc::log::MessageID HA_LEASE_UPDATE_CONFLICT
const isc::log::MessageID HA_LEASE_UPDATES_DISABLED
const isc::log::MessageID HA_LOCAL_DHCP_DISABLE
const int HA_SYNCING_ST
Synchronizing database state.
const isc::log::MessageID HA_RESET_FAILED
const isc::log::MessageID HA_STATE_TRANSITION
const isc::log::MessageID HA_CONFIG_LEASE_SYNCING_DISABLED_REMINDER
std::string stateToString(int state)
Returns state name.
const int HA_READY_ST
Server ready state, i.e. synchronized database, can enable DHCP service.
const isc::log::MessageID HA_TERMINATED_PARTNER_DID_NOT_RESTART
const isc::log::MessageID HA_SYNC_COMPLETE_NOTIFY_FAILED
const isc::log::MessageID HA_MAINTENANCE_STARTED
const isc::log::MessageID HA_LEASE_UPDATE_CREATE_UPDATE_FAILED_ON_PEER
const isc::log::MessageID HA_LEASE_UPDATE_FAILED
const isc::log::MessageID HA_STATE_TRANSITION_PASSIVE_BACKUP
boost::shared_ptr< ParkingLotHandle > ParkingLotHandlePtr
Pointer to the parking lot handle.
boost::shared_ptr< PostHttpRequestJson > PostHttpRequestJsonPtr
Pointer to PostHttpRequestJson.
boost::shared_ptr< HttpAuthConfig > HttpAuthConfigPtr
Type of shared pointers to HTTP authentication configuration.
boost::shared_ptr< HttpResponseJson > HttpResponseJsonPtr
Pointer to the HttpResponseJson object.
boost::shared_ptr< HttpResponse > HttpResponsePtr
Pointer to the HttpResponse object.
std::string ptimeToText(boost::posix_time::ptime t, size_t fsecs_precision=MAX_FSECS_PRECISION)
Converts ptime structure to text.
Defines the logger used by the top-level component of kea-lfc.
int http_response(CalloutHandle &handle)
This callout is called at the "http_response" hook.
static constexpr uint32_t STATE_RELEASED
Released lease held in the database for lease affinity.
HTTP request/response timeout value.
static const HttpVersion & HTTP_11()
HTTP version 1.1.