28#include <boost/pointer_cast.hpp>
39using namespace boost::posix_time;
45constexpr long WARN_CLOCK_SKEW = 30;
48constexpr long TERM_CLOCK_SKEW = 60;
51constexpr long MIN_TIME_SINCE_CLOCK_SKEW_WARN = 60;
61 poke_time_(boost::posix_time::microsec_clock::universal_time()),
76 std::lock_guard<std::mutex> lk(*
mutex_);
77 poke_time_ += boost::posix_time::seconds(secs);
79 poke_time_ += boost::posix_time::seconds(secs);
86 std::lock_guard<std::mutex> lk(*
mutex_);
96 std::lock_guard<std::mutex> lk(*
mutex_);
97 setPartnerStateInternal(state);
99 setPartnerStateInternal(state);
106 std::lock_guard<std::mutex> lk(*
mutex_);
107 setPartnerStateInternal(
"unavailable");
108 resetPartnerTimeInternal();
110 setPartnerStateInternal(
"unavailable");
111 resetPartnerTimeInternal();
116CommunicationState::setPartnerStateInternal(
const std::string& state) {
120 setCurrentPartnerStateTimeInternal();
131 ptime now = boost::posix_time::microsec_clock::universal_time();
133 std::lock_guard<std::mutex> lk(*
mutex_);
141CommunicationState::setCurrentPartnerStateTimeInternal() {
148 std::lock_guard<std::mutex> lk(*
mutex_);
158 std::lock_guard<std::mutex> lk(*
mutex_);
159 setPartnerScopesInternal(new_scopes);
161 setPartnerScopesInternal(new_scopes);
166CommunicationState::setPartnerScopesInternal(
ConstElementPtr new_scopes) {
167 if (!new_scopes || (new_scopes->getType() !=
Element::list)) {
169 " the received value is not a valid JSON list");
172 std::set<std::string> partner_scopes;
173 for (
unsigned i = 0; i < new_scopes->size(); ++i) {
174 auto scope = new_scopes->get(i);
177 " the received scope value is not a valid JSON string");
179 auto scope_str = scope->stringValue();
180 if (!scope_str.empty()) {
181 partner_scopes.insert(scope_str);
189 const std::function<
void()>& heartbeat_impl) {
191 std::lock_guard<std::mutex> lk(*
mutex_);
192 startHeartbeatInternal(interval, heartbeat_impl);
194 startHeartbeatInternal(interval, heartbeat_impl);
199CommunicationState::startHeartbeatInternal(
const long interval,
200 const std::function<
void()>& heartbeat_impl) {
201 bool settings_modified =
false;
205 if (heartbeat_impl) {
206 settings_modified =
true;
213 " to the heartbeat implementation is not specified");
219 settings_modified |= (
interval_ != interval);
226 isc_throw(BadValue,
"unable to start heartbeat when interval"
227 " for the heartbeat timer is not specified");
234 if (settings_modified) {
242 std::lock_guard<std::mutex> lk(*
mutex_);
243 stopHeartbeatInternal();
245 stopHeartbeatInternal();
250CommunicationState::stopHeartbeatInternal() {
262 std::lock_guard<std::mutex> lk(*
mutex_);
263 return (
static_cast<bool>(
timer_));
265 return (
static_cast<bool>(
timer_));
269boost::posix_time::time_duration
272 std::lock_guard<std::mutex> lk(*
mutex_);
273 return (updatePokeTimeInternal());
275 return (updatePokeTimeInternal());
279boost::posix_time::time_duration
280CommunicationState::updatePokeTimeInternal() {
282 boost::posix_time::ptime prev_poke_time =
poke_time_;
284 poke_time_ = boost::posix_time::microsec_clock::universal_time();
291 std::lock_guard<std::mutex> lk(*
mutex_);
299CommunicationState::pokeInternal() {
301 boost::posix_time::time_duration duration_since_poke = updatePokeTimeInternal();
314 if (duration_since_poke.total_seconds() > 0) {
318 startHeartbeatInternal();
326 std::lock_guard<std::mutex> lk(*
mutex_);
327 return (getDurationInMillisecsInternal());
329 return (getDurationInMillisecsInternal());
334CommunicationState::getDurationInMillisecsInternal()
const {
335 ptime now = boost::posix_time::microsec_clock::universal_time();
337 return (duration.total_milliseconds());
347 const uint16_t option_type) {
348 std::vector<uint8_t> client_id;
349 OptionPtr opt_client_id = message->getOption(option_type);
351 client_id = opt_client_id->getData();
364 std::lock_guard<std::mutex> lk(*
mutex_);
373 const uint32_t lifetime) {
375 std::lock_guard<std::mutex> lk(*
mutex_);
385 std::lock_guard<std::mutex> lk(*
mutex_);
395 std::lock_guard<std::mutex> lk(*
mutex_);
405 std::lock_guard<std::mutex> lk(*
mutex_);
406 return (clockSkewShouldWarnInternal());
408 return (clockSkewShouldWarnInternal());
413CommunicationState::clockSkewShouldWarnInternal() {
415 if (isClockSkewGreater(WARN_CLOCK_SKEW)) {
422 ptime now = boost::posix_time::microsec_clock::universal_time();
429 (since_warn_duration.total_seconds() > MIN_TIME_SINCE_CLOCK_SKEW_WARN)) {
432 .arg(
config_->getThisServerName())
433 .arg(logFormatClockSkewInternal());
445 std::lock_guard<std::mutex> lk(*
mutex_);
447 return (clockSkewShouldTerminateInternal());
449 return (clockSkewShouldTerminateInternal());
454CommunicationState::clockSkewShouldTerminateInternal() {
455 if (isClockSkewGreater(TERM_CLOCK_SKEW)) {
457 .arg(
config_->getThisServerName())
458 .arg(logFormatClockSkewInternal());
467 std::lock_guard<std::mutex> lk(*
mutex_);
468 return (rejectedLeaseUpdatesShouldTerminateInternal());
470 return (rejectedLeaseUpdatesShouldTerminateInternal());
475CommunicationState::rejectedLeaseUpdatesShouldTerminateInternal() {
476 if (
config_->getMaxRejectedLeaseUpdates() &&
479 .arg(
config_->getThisServerName());
486CommunicationState::isClockSkewGreater(
const long seconds)
const {
494 std::lock_guard<std::mutex> lk(*
mutex_);
495 setPartnerTimeInternal(time_text);
497 setPartnerTimeInternal(time_text);
502CommunicationState::setPartnerTimeInternal(
const std::string& time_text) {
509CommunicationState::resetPartnerTimeInternal() {
510 clock_skew_ = boost::posix_time::time_duration(0, 0, 0, 0);
519 std::lock_guard<std::mutex> lk(*
mutex_);
520 return (logFormatClockSkewInternal());
522 return (logFormatClockSkewInternal());
527CommunicationState::logFormatClockSkewInternal()
const {
528 std::ostringstream os;
534 return (
"skew not initialized");
541 <<
", partner's clock is ";
545 os <<
"synchronized";
548 os <<
clock_skew_.invert_sign().total_seconds() <<
"s behind";
578 report->set(
"last-scopes", list);
579 report->set(
"communication-interrupted",
584 long long unacked_clients_left = 0;
586 unacked_clients_left =
static_cast<long long>(
config_->getMaxUnackedClients() -
589 report->set(
"unacked-clients-left",
Element::create(unacked_clients_left));
605 std::lock_guard<std::mutex> lk(*
mutex_);
615 std::lock_guard<std::mutex> lk(*
mutex_);
616 increaseUnsentUpdateCountInternal();
618 increaseUnsentUpdateCountInternal();
623CommunicationState::increaseUnsentUpdateCountInternal() {
636 std::lock_guard<std::mutex> lk(*
mutex_);
637 return (hasPartnerNewUnsentUpdatesInternal());
639 return (hasPartnerNewUnsentUpdatesInternal());
644CommunicationState::hasPartnerNewUnsentUpdatesInternal()
const {
652 std::lock_guard<std::mutex> lk(*
mutex_);
653 setPartnerUnsentUpdateCountInternal(unsent_update_count);
655 setPartnerUnsentUpdateCountInternal(unsent_update_count);
660CommunicationState::setPartnerUnsentUpdateCountInternal(uint64_t unsent_update_count) {
665boost::posix_time::ptime
670boost::posix_time::ptime
684 std::lock_guard<std::mutex> lk(*
mutex_);
694 Pkt4Ptr msg = boost::dynamic_pointer_cast<Pkt4>(message);
703 uint16_t secs = msg->getSecs();
708 if ((secs > 255) && ((secs & 0xFF) == 0)) {
709 secs = ((secs >> 8) | (secs << 8));
716 auto unacked = (secs * 1000 >
config_->getMaxAckDelay());
721 bool log_unacked =
false;
725 auto existing_request = idx.find(boost::make_tuple(msg->getHWAddr()->hwaddr_, client_id));
726 if (existing_request != idx.end()) {
731 if (!existing_request->unacked_ && unacked) {
732 ConnectingClient4 connecting_client{ msg->getHWAddr()->hwaddr_, client_id, unacked };
733 idx.replace(existing_request, connecting_client);
740 ConnectingClient4 connecting_client{ msg->getHWAddr()->hwaddr_, client_id, unacked };
741 idx.insert(connecting_client);
742 log_unacked = unacked;
749 .arg(
config_->getThisServerName())
750 .arg(message->getLabel());
756 unsigned unacked_left = 0;
758 if (
config_->getMaxUnackedClients() >= unacked_total) {
759 unacked_left =
config_->getMaxUnackedClients() - unacked_total + 1;
762 .arg(
config_->getThisServerName())
763 .arg(message->getLabel())
772 std::lock_guard<std::mutex> lk(*
mutex_);
781 return ((
config_->getMaxUnackedClients() == 0) ||
783 config_->getMaxUnackedClients()));
789 std::lock_guard<std::mutex> lk(*
mutex_);
799 std::lock_guard<std::mutex> lk(*
mutex_);
818 Pkt4Ptr msg = boost::dynamic_pointer_cast<Pkt4>(message);
820 isc_throw(
BadValue,
"DHCP message for which the lease update was rejected is not a DHCPv4 message");
823 RejectedClient4 client{ msg->getHWAddr()->hwaddr_, client_id, time(NULL) + lifetime };
824 auto existing_client =
rejected_clients_.find(boost::make_tuple(msg->getHWAddr()->hwaddr_, client_id));
839 Pkt4Ptr msg = boost::dynamic_pointer_cast<Pkt4>(message);
841 isc_throw(
BadValue,
"DHCP message for which the lease update was successful is not a DHCPv4 message");
844 auto existing_client =
rejected_clients_.find(boost::make_tuple(msg->getHWAddr()->hwaddr_, client_id));
866 std::lock_guard<std::mutex> lk(*
mutex_);
876 Pkt6Ptr msg = boost::dynamic_pointer_cast<Pkt6>(message);
888 auto unacked = (elapsed_time && elapsed_time->getValue() * 10 >
config_->getMaxAckDelay());
896 bool log_unacked =
false;
900 auto existing_request = idx.find(duid);
901 if (existing_request != idx.end()) {
906 if (!existing_request->unacked_ && unacked) {
908 idx.replace(existing_request, connecting_client);
916 idx.insert(connecting_client);
917 log_unacked = unacked;
924 .arg(
config_->getThisServerName())
925 .arg(message->getLabel());
931 unsigned unacked_left = 0;
933 if (
config_->getMaxUnackedClients() >= unacked_total) {
934 unacked_left =
config_->getMaxUnackedClients() - unacked_total + 1;
937 .arg(
config_->getThisServerName())
938 .arg(message->getLabel())
947 std::lock_guard<std::mutex> lk(*
mutex_);
956 return ((
config_->getMaxUnackedClients() == 0) ||
958 config_->getMaxUnackedClients()));
964 std::lock_guard<std::mutex> lk(*
mutex_);
974 std::lock_guard<std::mutex> lk(*
mutex_);
993 Pkt6Ptr msg = boost::dynamic_pointer_cast<Pkt6>(message);
995 isc_throw(
BadValue,
"DHCP message for which the lease update was rejected is not a DHCPv6 message");
1017 Pkt6Ptr msg = boost::dynamic_pointer_cast<Pkt6>(message);
1019 isc_throw(
BadValue,
"DHCP message for which the lease update was successful is not a DHCPv6 message");
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.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
virtual bool reportRejectedLeaseUpdateInternal(const dhcp::PktPtr &message, const uint32_t lifetime)
Marks that the lease update failed due to a conflict for the specified DHCP message.
virtual size_t getRejectedLeaseUpdatesCountInternal()
Returns the number of lease updates rejected by the partner.
virtual bool reportSuccessfulLeaseUpdateInternal(const dhcp::PktPtr &message)
Marks the lease update successful.
virtual size_t getUnackedClientsCount() const
Returns the current number of clients which haven't gotten a lease from the partner server.
virtual void clearRejectedLeaseUpdatesInternal()
Clears rejected client leases.
virtual void analyzeMessageInternal(const boost::shared_ptr< dhcp::Pkt > &message)
Checks if the DHCPv4 message appears to be unanswered.
virtual size_t getConnectingClientsCount() const
Returns the current number of clients which attempted to get a lease from the partner server.
virtual void analyzeMessage(const boost::shared_ptr< dhcp::Pkt > &message)
Checks if the DHCPv4 message appears to be unanswered.
RejectedClients4 rejected_clients_
Holds information about the clients for whom lease updates have been rejected by the partner.
virtual bool failureDetectedInternal() const
Checks if the partner failure has been detected based on the DHCP traffic analysis.
ConnectingClients4 connecting_clients_
Holds information about the clients attempting to contact the partner server while the servers are in...
virtual bool failureDetected() const
Checks if the partner failure has been detected based on the DHCP traffic analysis.
virtual void clearConnectingClients()
Removes information about the clients the partner server should respond to while communication with t...
CommunicationState4(const asiolink::IOServicePtr &io_service, const HAConfigPtr &config)
Constructor.
virtual void analyzeMessage(const boost::shared_ptr< dhcp::Pkt > &message)
Checks if the DHCPv6 message appears to be unanswered.
RejectedClients6 rejected_clients_
Holds information about the clients for whom lease updates have been rejected by the partner.
virtual size_t getRejectedLeaseUpdatesCountInternal()
Returns the number of lease updates rejected by the partner.
ConnectingClients6 connecting_clients_
Holds information about the clients attempting to contact the partner server while the servers are in...
CommunicationState6(const asiolink::IOServicePtr &io_service, const HAConfigPtr &config)
Constructor.
virtual bool reportSuccessfulLeaseUpdateInternal(const dhcp::PktPtr &message)
Marks the lease update successful.
virtual void clearConnectingClients()
Removes information about the clients the partner server should respond to while communication with t...
virtual bool failureDetected() const
Checks if the partner failure has been detected based on the DHCP traffic analysis.
virtual size_t getUnackedClientsCount() const
Returns the current number of clients which haven't gotten a lease from the partner server.
virtual bool failureDetectedInternal() const
Checks if the partner failure has been detected based on the DHCP traffic analysis.
virtual void analyzeMessageInternal(const boost::shared_ptr< dhcp::Pkt > &message)
Checks if the DHCPv6 message appears to be unanswered.
virtual bool reportRejectedLeaseUpdateInternal(const dhcp::PktPtr &message, const uint32_t lifetime=86400)
Marks that the lease update failed due to a conflict for the specified DHCP message.
virtual size_t getConnectingClientsCount() const
Returns the current number of clients which attempted to get a lease from the partner server.
virtual void clearRejectedLeaseUpdatesInternal()
Clears rejected client leases.
virtual size_t getConnectingClientsCount() const =0
Returns the current number of clients which attempted to get a lease from the partner server.
virtual bool reportRejectedLeaseUpdateInternal(const dhcp::PktPtr &message, const uint32_t lifetime)=0
Marks that the lease update failed due to a conflict for the specified DHCP message.
boost::posix_time::ptime partner_state_time_
Holds a time when partner was first seen in the current state.
virtual void clearRejectedLeaseUpdatesInternal()=0
Clears rejected client leases.
virtual size_t getUnackedClientsCount() const =0
Returns the current number of clients which haven't got the lease from the partner server.
virtual void clearConnectingClients()=0
Removes information about the clients the partner server should respond to while communication with t...
void clearRejectedLeaseUpdates()
Clears rejected client leases (MT safe).
void startHeartbeat(const long interval, const std::function< void()> &heartbeat_impl)
Starts recurring heartbeat (public interface).
uint64_t unsent_update_count_
Total number of unsent lease updates.
bool isCommunicationInterrupted() const
Checks if communication with the partner is interrupted.
void setPartnerScopes(data::ConstElementPtr new_scopes)
Sets partner scopes.
int getPartnerState() const
Returns last known state of the partner.
bool clockSkewShouldWarn()
Issues a warning about high clock skew between the active servers if one is warranted.
std::string logFormatClockSkew() const
Returns current clock skew value in the logger friendly format.
void setPartnerUnsentUpdateCount(uint64_t unsent_update_count)
Saves new total number of unsent lease updates from the partner.
void setPartnerState(const std::string &state)
Sets partner state.
bool clockSkewShouldTerminate()
Indicates whether the HA service should enter "terminated" state as a result of the clock skew exceed...
std::pair< uint64_t, uint64_t > partner_unsent_update_count_
Previous and current total number of unsent lease updates from the partner.
std::set< std::string > getPartnerScopes() const
Returns scopes served by the partner server.
virtual ~CommunicationState()
Destructor.
HAConfigPtr config_
High availability configuration.
bool isHeartbeatRunning() const
Checks if recurring heartbeat is running.
static size_t getRejectedLeaseUpdatesCountFromContainer(RejectedClientsType &rejected_clients)
Extracts the number of lease updates rejected by the partner from the specified container.
long interval_
Interval specified for the heartbeat.
void setPartnerUnavailable()
Sets partner state unavailable.
void stopHeartbeat()
Stops recurring heartbeat.
void increaseUnsentUpdateCount()
Increases a total number of unsent lease updates by 1.
void setPartnerTime(const std::string &time_text)
Provide partner's notion of time so the new clock skew can be calculated.
bool hasPartnerNewUnsentUpdates() const
Checks if the partner allocated new leases for which it hasn't sent any lease updates.
virtual bool reportSuccessfulLeaseUpdateInternal(const dhcp::PktPtr &message)=0
Marks the lease update successful.
asiolink::IOServicePtr io_service_
Pointer to the common IO service instance.
virtual size_t getRejectedLeaseUpdatesCountInternal()=0
Returns the number of lease updates rejected by the partner.
void modifyPokeTime(const long secs)
Modifies poke time by adding seconds to it.
const boost::scoped_ptr< std::mutex > mutex_
The mutex used to protect internal state.
data::ElementPtr getReport() const
Returns the report about current communication state.
boost::posix_time::ptime getPartnerTimeAtSkew() const
Retrieves the time of the partner node when skew was last calculated.
boost::posix_time::time_duration clock_skew_
Clock skew between the active servers.
size_t getAnalyzedMessagesCount() const
Returns the number of analyzed messages while being in the communications interrupted state.
size_t analyzed_messages_count_
Total number of analyzed messages to be responded by partner.
std::function< void()> heartbeat_impl_
Pointer to the function providing heartbeat implementation.
boost::posix_time::ptime poke_time_
Last poke time.
boost::posix_time::time_duration updatePokeTime()
Update the poke time and compute the duration.
bool reportSuccessfulLeaseUpdate(const dhcp::PktPtr &message)
Marks the lease update successful (MT safe).
boost::posix_time::ptime partner_time_at_skew_
Partner reported time when skew was calculated.
CommunicationState(const asiolink::IOServicePtr &io_service, const HAConfigPtr &config)
Constructor.
boost::posix_time::time_duration getDurationSincePartnerStateTime() const
Returns the duration since the partner was first seen in the current state.
int partner_state_
Last known state of the partner server.
boost::posix_time::ptime last_clock_skew_warn_
Holds a time when last warning about too high clock skew was issued.
std::set< std::string > partner_scopes_
Last known set of scopes served by the partner server.
static std::vector< uint8_t > getClientId(const dhcp::PktPtr &message, const uint16_t option_type)
Convenience function attempting to retrieve client identifier from the DHCP message.
uint64_t getUnsentUpdateCount() const
Returns a total number of unsent lease updates.
bool rejectedLeaseUpdatesShouldTerminate()
Indicates whether the HA service should enter "terminated" state due to excessive number of rejected ...
boost::posix_time::ptime getMyTimeAtSkew() const
Retrieves the time of the local node when skew was last calculated.
boost::posix_time::ptime my_time_at_skew_
My time when skew was calculated.
int64_t getDurationInMillisecs() const
Returns duration between the poke time and current time.
bool reportRejectedLeaseUpdate(const dhcp::PktPtr &message, const uint32_t lifetime=86400)
Marks that the lease update failed due to a conflict for the specified DHCP message (MT safe).
size_t getRejectedLeaseUpdatesCount()
Returns the number of lease updates rejected by the partner (MT safe).
asiolink::IntervalTimerPtr timer_
Interval timer triggering heartbeat commands.
void poke()
Pokes the communication state.
This class parses and generates time values used in HTTP.
boost::posix_time::ptime getPtime() const
Returns time encapsulated by this class.
static HttpDateTime fromRfc1123(const std::string &time_string)
Creates an instance from a string containing time value formatted as specified in RFC 1123.
static MultiThreadingMgr & instance()
Returns a single instance of Multi Threading Manager.
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
OptionInt< uint16_t > OptionUint16
boost::shared_ptr< OptionUint16 > OptionUint16Ptr
#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.
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.
@ DHO_DHCP_CLIENT_IDENTIFIER
boost::shared_ptr< Pkt4 > Pkt4Ptr
A pointer to Pkt4 object.
boost::shared_ptr< Pkt6 > Pkt6Ptr
A pointer to Pkt6 packet.
boost::shared_ptr< Option > OptionPtr
const isc::log::MessageID HA_COMMUNICATION_INTERRUPTED_CLIENT4_UNACKED
const isc::log::MessageID HA_COMMUNICATION_INTERRUPTED_CLIENT6
isc::log::Logger ha_logger("ha-hooks")
const isc::log::MessageID HA_HIGH_CLOCK_SKEW_CAUSED_TERMINATION
const isc::log::MessageID HA_LEASE_UPDATE_REJECTS_CAUSED_TERMINATION
boost::shared_ptr< HAConfig > HAConfigPtr
Pointer to the High Availability configuration structure.
const isc::log::MessageID HA_COMMUNICATION_INTERRUPTED_CLIENT6_UNACKED
std::string stateToString(int state)
Returns state name.
const isc::log::MessageID HA_COMMUNICATION_INTERRUPTED_CLIENT4
int stringToState(const std::string &state_name)
Returns state for a given name.
const isc::log::MessageID HA_HIGH_CLOCK_SKEW
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.
Structure holding information about the client which has sent the packet being analyzed.
Structure holding information about the client who has a rejected lease update.
Structure holding information about a client which sent a packet being analyzed.
Structure holding information about the client who has a rejected lease update.