13 #include <boost/bind/bind.hpp>
14 #include <boost/date_time/posix_time/posix_time.hpp>
15 #include <boost/statechart/custom_reaction.hpp>
16 #include <boost/statechart/event.hpp>
17 #include <boost/statechart/simple_state.hpp>
18 #include <boost/statechart/state.hpp>
19 #include <boost/statechart/state_machine.hpp>
20 #include <boost/statechart/transition.hpp>
21 #include <boost/statechart/in_state_reaction.hpp>
29 #include <sandesh/sandesh_constants.h>
30 #include <sandesh/sandesh_types.h>
31 #include <sandesh/sandesh.h>
32 #include <sandesh/sandesh_uve.h>
33 #include <sandesh/sandesh_uve_types.h>
34 #include <sandesh/sandesh_statistics.h>
37 using boost::system::error_code;
42 using process::ConnectionType;
43 using process::ConnectionStatus;
44 using namespace boost::placeholders;
46 namespace mpl = boost::mpl;
47 namespace sc = boost::statechart;
49 #define SM_LOG(_Level, _Msg) \
51 if (LoggingDisabled()) break; \
52 log4cplus::Logger _Xlogger = Sandesh::logger(); \
53 if (_Xlogger.isEnabledFor(log4cplus::_Level##_LOG_LEVEL)) { \
54 log4cplus::tostringstream _Xbuf; \
56 _Xlogger.forcedLog(log4cplus::_Level##_LOG_LEVEL, \
61 #define SESSION_LOG(session) \
62 SANDESH_LOG(DEBUG, ((session) ? (session)->ToString() : "*") << ":" << Name())
69 static const char *
Name() {
77 static const char *
Name() {
85 collectors_(collectors) {
87 static const char *
Name() {
88 return "EvCollectorUpdate";
96 static const char *
Name() {
97 return "EvIdleHoldTimerExpired";
100 return !timer_->cancelled();
109 return "EvConnectTimerExpired";
112 if (timer_->cancelled()) {
125 return "EvTcpConnected";
136 return "EvTcpConnectFail";
159 return "EvTcpDeleteSession";
169 return "EvSandeshSend";
176 const std::string &msg_type,
const uint32_t &header_offset) :
177 msg(msg), header(header), msg_type(msg_type), header_offset(header_offset) {
180 return "EvSandeshMessageRecv";
205 &SandeshClientSMImpl::ReleaseSandesh<Ev> >
reaction;
211 &SandeshClientSMImpl::DeleteTcpSession<Ev> >
reaction;
215 struct Idle :
public sc::state<Idle, SandeshClientSMImpl> {
217 sc::custom_reaction<EvStart>,
218 sc::custom_reaction<EvStop>,
219 sc::custom_reaction<EvIdleHoldTimerExpired>,
220 sc::custom_reaction<EvCollectorUpdate>,
225 Idle(my_context ctx) : my_base(ctx) {
241 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
242 std::string(), ConnectionStatus::INIT,
248 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
249 std::string(), ConnectionStatus::DOWN,
253 return transit<Disconnect>();
255 return discard_event();
261 return discard_event();
267 return discard_event();
272 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
273 std::string(), ConnectionStatus::INIT,
275 state_machine->
StateName() +
" : " + event.
Name() +
" -> Connect");
276 return transit<Connect>();
280 struct Disconnect :
public sc::state<Disconnect, SandeshClientSMImpl> {
283 sc::custom_reaction<EvCollectorUpdate>,
299 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
300 std::string(), ConnectionStatus::INIT,
304 return transit<Connect>();
308 struct Connect :
public sc::state<Connect, SandeshClientSMImpl> {
311 sc::custom_reaction<EvConnectTimerExpired>,
312 sc::custom_reaction<EvTcpConnected>,
313 sc::custom_reaction<EvTcpConnectFail>,
314 sc::custom_reaction<EvTcpClose>,
315 sc::custom_reaction<EvCollectorUpdate>,
320 static const int kConnectTimeout = 60;
325 StartSession(state_machine);
327 SM_LOG(DEBUG, state_machine->
StateName() <<
" : " <<
"Start Connect timer " <<
342 return ToIdle(state_machine, event.
Name());
350 return ToIdle(state_machine, event.
Name());
356 event.
Name() <<
" : " <<
"Cancelling Connect timer");
360 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
365 return transit<ClientInit>();
372 return ToIdle(state_machine, event.
Name());
378 return ToIdle(state_machine, event.
Name());
380 return discard_event();
388 state_machine, _1, _2),
390 state_machine, _2, _1),
391 state_machine->
server()));
397 const char *event_name) {
399 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
400 std::string(), ConnectionStatus::DOWN,
402 state_machine->
StateName() +
" : " + event_name);
406 return transit<Idle>();
410 struct ClientInit :
public sc::state<ClientInit, SandeshClientSMImpl> {
413 sc::custom_reaction<EvConnectTimerExpired>,
414 sc::custom_reaction<EvTcpClose>,
415 sc::custom_reaction<EvSandeshMessageRecv>,
416 sc::custom_reaction<EvSandeshSend>,
417 sc::custom_reaction<EvCollectorUpdate>,
440 return ToIdle(state_machine, event.
Name());
447 return ToIdle(state_machine, event.
Name());
456 return ToIdle(state_machine, event.
Name());
460 if (event.
header.get_Hints() & g_sandesh_constants.SANDESH_CONTROL_HINT) {
462 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
463 std::string(), ConnectionStatus::UP,
466 return transit<Established>();
468 return discard_event();
475 " : " << snh->
Name());
482 SandeshTxDropReason::WrongClientSMState);
483 SM_LOG(INFO,
"Received UVE message in wrong state : " << snh->
Name());
485 return discard_event();
488 SM_LOG(INFO,
"Could not EnQ Sandesh :" << snh->
Name());
491 return discard_event();
497 return ToIdle(state_machine, event.
Name());
499 return discard_event();
503 const char *event_name) {
505 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
506 std::string(), ConnectionStatus::DOWN,
508 state_machine->
StateName() +
" : " + event_name);
512 return transit<Idle>();
516 struct Established :
public sc::state<Established, SandeshClientSMImpl> {
519 sc::custom_reaction<EvTcpClose>,
520 sc::custom_reaction<EvSandeshMessageRecv>,
521 sc::custom_reaction<EvSandeshSend>,
522 sc::custom_reaction<EvCollectorUpdate>,
532 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
533 std::string(), ConnectionStatus::UP,
549 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
550 std::string(), ConnectionStatus::INIT,
555 return transit<Connect>();
557 return ToIdle(state_machine, event.
Name());
567 return ToIdle(state_machine, event.
Name());
569 return discard_event();
576 SM_LOG(ERROR,
"Could not EnQ Sandesh :" << event.
snh->
Name());
579 return discard_event();
586 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
587 std::string(), ConnectionStatus::INIT,
592 return transit<Connect>();
594 return discard_event();
598 const char *event_name) {
600 ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
601 std::string(), ConnectionStatus::DOWN,
603 state_machine->
StateName() +
" : " + event_name);
606 return transit<Idle>();
617 reset_idle_hold_time();
631 set_idle_hold_time(idle_hold_time() ? idle_hold_time() : kIdleHoldTime);
633 CancelIdleHoldTimer();
635 set_session(NULL, event.enq_);
645 SandeshTxDropReason::WrongClientSMState);
646 SM_LOG(DEBUG,
"Wrong state: " << StateName() <<
" for event: " <<
647 event.Name() <<
" message: " << snh->
Name());
653 GetMgr()->DeleteSMSession(event.session);
657 connect_timer_->Start(seconds * 1000,
663 connect_timer_->Cancel();
667 return connect_timer_->running();
671 if (idle_hold_time_ <= 0)
674 idle_hold_timer_->Start(idle_hold_time_,
680 idle_hold_timer_->Cancel();
684 return idle_hold_timer_->running();
691 connect_timer_->Fire();
695 idle_hold_timer_->Fire();
702 SM_LOG(ERROR, name +
" error: " + error);
708 SM_LOG(DEBUG, server() <<
" "
709 <<
"EvConnectTimerExpired in state " << StateName());
723 assert((session != NULL) == (sandesh_session != NULL));
724 std::string session_s = session ? session->
ToString() :
"*";
727 SM_LOG(DEBUG, session_s <<
" " << __func__ <<
728 " " <<
"TCP Connected");
732 SM_LOG(DEBUG, session_s <<
" " << __func__ <<
733 " " <<
"TCP Connect Failed");
737 SM_LOG(DEBUG, session_s <<
" " << __func__ <<
738 " " <<
"TCP Connection Closed");
743 SM_LOG(DEBUG, session_s <<
" " <<
"Unknown event: " <<
760 const std::string &msg) {
762 SandeshHeader header;
763 std::string message_type;
764 uint32_t xml_offset = 0;
770 SM_LOG(ERROR,
"OnMessage in state: " << StateName() <<
": Extract "
771 <<
" FAILED(" << ret <<
")");
775 if (header.get_Hints() & g_sandesh_constants.SANDESH_CONTROL_HINT) {
776 SM_LOG(INFO,
"OnMessage control in state: " << StateName() );
806 int backoff = std::min(attempts_, 6);
807 return std::min(backoff ? 1 << (backoff - 1) : 0, kConnectInterval);
811 UpdateEventStats(event,
true,
false);
815 UpdateEventStats(event,
false,
false);
819 UpdateEventStats(event,
true,
true);
823 UpdateEventStats(event,
false,
true);
827 bool enqueue,
bool fail) {
828 std::string event_name(
TYPE_NAME(event));
829 std::scoped_lock lock(mutex_);
830 event_stats_.Update(event_name, enqueue, fail);
834 if (deleted_)
return true;
842 UpdateEventDequeue(*ec.
event);
843 process_event(*ec.
event);
847 UpdateEventDequeueFail(*ec.
event);
861 template<
typename Ev>
864 template<
typename T,
bool (T::*)(SandeshClientSMImpl *) const>
struct SFINAE {};
866 template<
typename T>
static int Test(...);
867 static const bool Has =
sizeof(Test<Ev>(0)) ==
sizeof(
char);
870 template <
typename Ev,
bool has_val
idate>
875 template <
typename Ev>
878 return boost::bind(&Ev::validate, event, _1);
882 template <
typename Ev>
884 if (deleted_)
return;
887 ec.
event =
event.intrusive_from_this();
889 if (!work_queue_.Enqueue(ec)) {
894 UpdateEventEnqueue(event);
900 int sm_task_instance,
int sm_task_id,
bool periodicuve)
902 work_queue_(sm_task_id, sm_task_instance,
904 connect_timer_(
TimerManager::CreateTimer(*
evm->io_service(),
"Client Connect timer", sm_task_id, sm_task_instance)),
905 idle_hold_timer_(
TimerManager::CreateTimer(*
evm->io_service(),
"Client Idle hold timer", sm_task_id, sm_task_instance)),
906 statistics_timer_(
TimerManager::CreateTimer(*
evm->io_service(),
"Client Tick and Statistics timer", sm_task_id, sm_task_instance)),
908 statistics_timer_interval_(kTickInterval),
909 periodicuve_(periodicuve),
914 coll_name_(string()) {
923 std::scoped_lock lock(
mutex_);
971 std::vector<SandeshStateMachineEvStats> ev_stats;
973 std::scoped_lock lock(
mutex_);
977 ModuleClientState mcs;
982 SandeshStateMachineStats sm_stats;
983 sm_stats.set_ev_stats(ev_stats);
989 mcs.set_sm_stats(sm_stats);
994 SocketIOStats rx_stats;
996 mcs.set_session_rx_socket_stats(rx_stats);
997 SocketIOStats tx_stats;
999 mcs.set_session_tx_socket_stats(tx_stats);
1001 SandeshModuleClientTrace::Send(mcs);
1004 map<string,uint32_t> inpMap;
1011 const std::vector<TcpServer::Endpoint>& collectors) {
1016 std::vector<TcpServer::Endpoint>& collectors) {
1038 const std::vector<TcpServer::Endpoint>& collectors) {
1042 if (
server() != collector) {
1053 if (
server() != collector) {
1063 int sm_task_id,
bool periodicuve) {
void GetCollectors(std::vector< TcpServer::Endpoint > &collectors)
int statistics_timer_interval_
void UpdateEventStats(const sc::event_base &event, bool enqueue, bool fail)
void UpdateEventDequeueFail(const sc::event_base &event)
bool send_session(Sandesh *snh)
void UpdateEventEnqueueFail(const sc::event_base &event)
int idle_hold_time() const
bool CollectorUpdate(const std::vector< TcpServer::Endpoint > &collectors)
void OnSessionEvent(TcpSession *session, TcpSession::Event event)
std::vector< TcpServer::Endpoint > collectors_
std::string generator_key_
void Enqueue(const Ev &event)
bool StatisticsTimerExpired()
virtual ~SandeshClientSMImpl()
void ReleaseSandesh(const Ev &event)
TcpServer::Endpoint GetNextCollector()
void CancelIdleHoldTimer()
void EnqueDelSession(SandeshSession *session)
const std::string last_event() const
void SetAdminState(bool down)
void DeleteTcpSession(const Ev &event)
bool ConnectTimerRunning()
bool OnMessage(SandeshSession *session, const std::string &msg)
void StartConnectTimer(int seconds)
Timer * statistics_timer_
void IdleHoldTimerFired()
bool ConnectTimerExpired()
bool SendSandeshUVE(Sandesh *snh)
void SetCollectors(const std::vector< TcpServer::Endpoint > &collectors)
WorkQueue< EventContainer > work_queue_
TcpServer::Endpoint GetCollector() const
bool IdleHoldTimerRunning()
void set_idle_hold_time(int idle_hold_time)
bool SendSandesh(Sandesh *snh)
void TimerErrorHanlder(std::string name, std::string error)
SandeshEventStatistics event_stats_
void UpdateEventDequeue(const sc::event_base &event)
void connect_attempts_clear()
bool IdleHoldTimerExpired()
bool DequeueEvent(EventContainer ec)
void set_state(State state)
void CancelConnectTimer()
const std::string & LastStateName() const
static const int kConnectInterval
void OnIdle(const Ev &event)
void StartIdleHoldTimer()
void StartStatisticsTimer()
const std::string & StateName() const
void unconsumed_event(const sc::event_base &event)
void UpdateEventEnqueue(const sc::event_base &event)
int GetConnectTime() const
void set_collector_name(const std::string &cname)
void connect_attempts_inc()
void set_session(SandeshSession *session, bool enq=true)
SandeshClientSMImpl(EventManager *evm, Mgr *mgr, int sm_task_instance, int sm_task_id, bool periodicuve)
virtual bool ReceiveMsg(const std::string &msg, const SandeshHeader &header, const std::string &sandesh_name, const uint32_t header_offset)=0
virtual void InitializeSMSession(int connects)=0
virtual StatsClient * stats_client() const =0
virtual SandeshSession * CreateSMSession(TcpSession::EventObserver eocb, SandeshReceiveMsgCb rmcb, TcpServer::Endpoint ep)=0
SandeshSession * session()
void set_server(TcpServer::Endpoint e)
std::atomic< State > state_
TcpServer::Endpoint server()
static SandeshClientSM * CreateClientSM(EventManager *evm, Mgr *mgr, int sm_task_instance, int sm_task_id, bool periodicuve)
void Get(std::vector< SandeshStateMachineEvStats > *ev_stats) const
static int ExtractMsgHeader(const std::string &msg, SandeshHeader &header, std::string &msg_type, uint32_t &header_offset)
void set_stats_client(StatsClient *stats_client)
Sandesh::SandeshQueue * send_queue()
const SandeshSessionStats & GetStats() const
static void SyncAllMaps(const std::map< std::string, uint32_t > &, bool periodic=false)
static void UpdateTxMsgFailStats(const std::string &msg_name, uint64_t bytes, SandeshTxDropReason::type dreason)
static std::string source()
virtual const char * Name() const
SandeshType::type type() const
static bool IsLoggingDroppedAllowed(SandeshType::type)
static std::string module()
static std::string instance_id()
static std::string node_type()
virtual std::string ToString() const =0
boost::asio::ip::tcp::endpoint Endpoint
virtual std::string ToString() const
void GetRxSocketStats(SocketIOStats *socket_stats) const
Endpoint remote_endpoint() const
void GetTxSocketStats(SocketIOStats *socket_stats) const
static bool DeleteTimer(Timer *Timer)
bool Start(int time, Handler handler, ErrorHandler error_handler=NULL)
void Shutdown(bool delete_entries=true)
size_t max_queue_len() const
bool IsQueueEmpty() const
#define SANDESH_LOG(_Level, _Msg)
#define SM_LOG(_Level, _Msg)
#define SESSION_LOG(session)
static const std::string state_names[]
boost::function< bool(StateMachine *)> EvValidate
static char Test(SFINAE< T, &T::validate > *)
boost::intrusive_ptr< const sc::event_base > event
EvValidate operator()(const Ev *event)
EvValidate operator()(const Ev *event)
sc::result react(const EvCollectorUpdate &event)
sc::result react(const EvConnectTimerExpired &event)
sc::result react(const EvTcpClose &event)
sc::result react(const EvSandeshMessageRecv &event)
mpl::list< TransitToIdle< EvStop >::reaction, sc::custom_reaction< EvConnectTimerExpired >, sc::custom_reaction< EvTcpClose >, sc::custom_reaction< EvSandeshMessageRecv >, sc::custom_reaction< EvSandeshSend >, sc::custom_reaction< EvCollectorUpdate >, DeleteTcpSession< EvTcpDeleteSession >::reaction > reactions
ClientInit(my_context ctx)
sc::result ToIdle(SandeshClientSMImpl *state_machine, const char *event_name)
sc::result react(const EvSandeshSend &event)
sc::result react(const EvTcpConnected &event)
sc::result react(const EvTcpClose &event)
sc::result react(const EvConnectTimerExpired &event)
void StartSession(SandeshClientSMImpl *state_machine)
sc::result ToIdle(SandeshClientSMImpl *state_machine, const char *event_name)
sc::result react(const EvTcpConnectFail &event)
sc::result react(const EvCollectorUpdate &event)
mpl::list< TransitToIdle< EvStop >::reaction, sc::custom_reaction< EvConnectTimerExpired >, sc::custom_reaction< EvTcpConnected >, sc::custom_reaction< EvTcpConnectFail >, sc::custom_reaction< EvTcpClose >, sc::custom_reaction< EvCollectorUpdate >, ReleaseSandesh< EvSandeshSend >::reaction, DeleteTcpSession< EvTcpDeleteSession >::reaction > reactions
sc::in_state_reaction< Ev, SandeshClientSMImpl, &SandeshClientSMImpl::DeleteTcpSession< Ev > > reaction
sc::result react(const EvCollectorUpdate &event)
Disconnect(my_context ctx)
mpl::list< TransitToIdle< EvStop >::reaction, sc::custom_reaction< EvCollectorUpdate >, ReleaseSandesh< EvSandeshSend >::reaction, DeleteTcpSession< EvTcpDeleteSession >::reaction > reactions
sc::result ToIdle(SandeshClientSMImpl *state_machine, const char *event_name)
sc::result react(const EvCollectorUpdate &event)
mpl::list< TransitToIdle< EvStop >::reaction, sc::custom_reaction< EvTcpClose >, sc::custom_reaction< EvSandeshMessageRecv >, sc::custom_reaction< EvSandeshSend >, sc::custom_reaction< EvCollectorUpdate >, DeleteTcpSession< EvTcpDeleteSession >::reaction > reactions
sc::result react(const EvSandeshMessageRecv &event)
sc::result react(const EvTcpClose &event)
sc::result react(const EvSandeshSend &event)
Established(my_context ctx)
static const char * Name()
std::vector< TcpServer::Endpoint > collectors_
EvCollectorUpdate(const std::vector< TcpServer::Endpoint > &collectors)
bool validate(SandeshClientSMImpl *state_machine) const
static const char * Name()
EvConnectTimerExpired(Timer *timer)
EvIdleHoldTimerExpired(Timer *timer)
static const char * Name()
const std::string msg_type
static const char * Name()
EvSandeshMessageRecv(const std::string &msg, const SandeshHeader &header, const std::string &msg_type, const uint32_t &header_offset)
const uint32_t header_offset
const SandeshHeader header
EvSandeshSend(Sandesh *snh)
static const char * Name()
static const char * Name()
static const char * Name()
static const char * Name()
EvTcpClose(SandeshSession *session)
static const char * Name()
EvTcpConnectFail(SandeshSession *session)
static const char * Name()
EvTcpConnected(SandeshSession *session)
static const char * Name()
EvTcpDeleteSession(SandeshSession *session)
sc::result react(const EvCollectorUpdate &event)
sc::result react(const EvStop &event)
mpl::list< sc::custom_reaction< EvStart >, sc::custom_reaction< EvStop >, sc::custom_reaction< EvIdleHoldTimerExpired >, sc::custom_reaction< EvCollectorUpdate >, ReleaseSandesh< EvSandeshSend >::reaction, DeleteTcpSession< EvTcpDeleteSession >::reaction > reactions
sc::result react(const EvStart &event)
sc::result react(const EvIdleHoldTimerExpired &event)
sc::in_state_reaction< Ev, SandeshClientSMImpl, &SandeshClientSMImpl::ReleaseSandesh< Ev > > reaction
sc::transition< Ev, Idle, SandeshClientSMImpl, &SandeshClientSMImpl::OnIdle< Ev > > reaction