OpenSDN source code
sandesh_client_sm.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 
6 //
7 // sandesh_client_sm.cc
8 //
9 // Sandesh Client State Machine
10 //
11 
12 #include <typeinfo>
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>
22 
23 #include <base/logging.h>
24 #include <base/timer.h>
25 #include <base/task_annotations.h>
26 #include <base/connection_info.h>
27 #include <io/event_manager.h>
28 
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>
35 #include "sandesh_client_sm_priv.h"
36 
37 using boost::system::error_code;
38 using std::string;
39 using std::map;
40 using std::vector;
42 using process::ConnectionType;
43 using process::ConnectionStatus;
44 using namespace boost::placeholders;
45 
46 namespace mpl = boost::mpl;
47 namespace sc = boost::statechart;
48 
49 #define SM_LOG(_Level, _Msg) \
50  do { \
51  if (LoggingDisabled()) break; \
52  log4cplus::Logger _Xlogger = Sandesh::logger(); \
53  if (_Xlogger.isEnabledFor(log4cplus::_Level##_LOG_LEVEL)) { \
54  log4cplus::tostringstream _Xbuf; \
55  _Xbuf << _Msg; \
56  _Xlogger.forcedLog(log4cplus::_Level##_LOG_LEVEL, \
57  _Xbuf.str()); \
58  } \
59  } while (false)
60 
61 #define SESSION_LOG(session) \
62  SANDESH_LOG(DEBUG, ((session) ? (session)->ToString() : "*") << ":" << Name())
63 
64 
65 namespace scm {
66 
67 // events
68 struct EvStart : sc::event<EvStart> {
69  static const char * Name() {
70  return "EvStart";
71  }
72 };
73 
74 struct EvStop : sc::event<EvStop> {
75  EvStop() : enq_(true) {}
76  EvStop(bool enq) : enq_(enq) {}
77  static const char * Name() {
78  return "EvStop";
79  }
80  bool enq_;
81 };
82 
83 struct EvCollectorUpdate : sc::event<EvCollectorUpdate> {
84  EvCollectorUpdate(const std::vector<TcpServer::Endpoint> &collectors) :
85  collectors_(collectors) {
86  }
87  static const char * Name() {
88  return "EvCollectorUpdate";
89  }
90  std::vector<TcpServer::Endpoint> collectors_;
91 };
92 
93 struct EvIdleHoldTimerExpired : sc::event<EvIdleHoldTimerExpired> {
94  EvIdleHoldTimerExpired(Timer *timer) : timer_(timer){
95  }
96  static const char * Name() {
97  return "EvIdleHoldTimerExpired";
98  }
99  bool validate() const {
100  return !timer_->cancelled();
101  }
103 };
104 
105 struct EvConnectTimerExpired : sc::event<EvConnectTimerExpired> {
106  EvConnectTimerExpired(Timer *timer) : timer_(timer) {
107  }
108  static const char * Name() {
109  return "EvConnectTimerExpired";
110  }
111  bool validate(SandeshClientSMImpl *state_machine) const {
112  if (timer_->cancelled()) {
113  return false;
114  }
115  return true;
116  }
118 };
119 
120 struct EvTcpConnected : sc::event<EvTcpConnected> {
121  EvTcpConnected(SandeshSession *session) : session(session) {
122  SESSION_LOG(session);
123  }
124  static const char * Name() {
125  return "EvTcpConnected";
126  }
127 
129 };
130 
131 struct EvTcpConnectFail : sc::event<EvTcpConnectFail> {
132  EvTcpConnectFail(SandeshSession *session) : session(session) {
133  SESSION_LOG(session);
134  }
135  static const char * Name() {
136  return "EvTcpConnectFail";
137  }
138 
140 };
141 
142 
143 struct EvTcpClose : sc::event<EvTcpClose> {
144  EvTcpClose(SandeshSession *session) : session(session) {
145  SESSION_LOG(session);
146  };
147  static const char * Name() {
148  return "EvTcpClose";
149  }
150 
152 };
153 
154 // Used to defer the session delete after all events currently on the queue.
155 struct EvTcpDeleteSession : sc::event<EvTcpDeleteSession> {
156  EvTcpDeleteSession(SandeshSession *session) : session(session) {
157  }
158  static const char *Name() {
159  return "EvTcpDeleteSession";
160  }
162 };
163 
164 struct EvSandeshSend : sc::event<EvSandeshSend> {
166  snh(snh) {
167  }
168  static const char * Name() {
169  return "EvSandeshSend";
170  }
172 };
173 
174 struct EvSandeshMessageRecv : sc::event<EvSandeshMessageRecv> {
175  EvSandeshMessageRecv(const std::string &msg, const SandeshHeader& header,
176  const std::string &msg_type, const uint32_t &header_offset) :
177  msg(msg), header(header), msg_type(msg_type), header_offset(header_offset) {
178  };
179  static const char * Name() {
180  return "EvSandeshMessageRecv";
181  }
182  const std::string msg;
183  const SandeshHeader header;
184  const std::string msg_type;
185  const uint32_t header_offset;
186 };
187 
188 
189 // states
190 struct Idle;
191 struct Connect;
192 struct Disconnect;
193 struct ClientInit;
194 struct Established;
195 
196 template <class Ev>
198  typedef sc::transition<Ev, Idle, SandeshClientSMImpl,
199  &SandeshClientSMImpl::OnIdle<Ev> > reaction;
200 };
201 
202 template <class Ev>
204  typedef sc::in_state_reaction<Ev, SandeshClientSMImpl,
205  &SandeshClientSMImpl::ReleaseSandesh<Ev> > reaction;
206 };
207 
208 template <class Ev>
210  typedef sc::in_state_reaction<Ev, SandeshClientSMImpl,
211  &SandeshClientSMImpl::DeleteTcpSession<Ev> > reaction;
212 };
213 
214 
215 struct Idle : public sc::state<Idle, SandeshClientSMImpl> {
216  typedef mpl::list<
217  sc::custom_reaction<EvStart>,
218  sc::custom_reaction<EvStop>,
219  sc::custom_reaction<EvIdleHoldTimerExpired>,
220  sc::custom_reaction<EvCollectorUpdate>,
224 
225  Idle(my_context ctx) : my_base(ctx) {
226  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
227  state_machine->set_state(SandeshClientSM::IDLE);
228  SM_LOG(DEBUG, state_machine->StateName());
229  state_machine->SendUVE();
230  }
231 
232  ~Idle() {
233  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
234  state_machine->CancelIdleHoldTimer();
235  }
236 
237  sc::result react(const EvStart &event) {
238  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
239  if (state_machine->idle_hold_time()) {
240  // Update connection info
241  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
242  std::string(), ConnectionStatus::INIT,
243  state_machine->server(),
244  state_machine->StateName() + " : " + event.Name());
245  state_machine->StartIdleHoldTimer();
246  } else {
247  // Update connection info
248  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
249  std::string(), ConnectionStatus::DOWN,
250  state_machine->server(),
251  state_machine->StateName() + " : " + event.Name() +
252  " -> Disconnect");
253  return transit<Disconnect>();
254  }
255  return discard_event();
256  }
257 
258  sc::result react(const EvStop &event) {
259  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
260  state_machine->CancelIdleHoldTimer();
261  return discard_event();
262  }
263 
264  sc::result react(const EvCollectorUpdate &event) {
265  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
266  state_machine->CollectorUpdate(event.collectors_);
267  return discard_event();
268  }
269  sc::result react(const EvIdleHoldTimerExpired &event) {
270  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
271  // Update connection info
272  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
273  std::string(), ConnectionStatus::INIT,
274  state_machine->server(),
275  state_machine->StateName() + " : " + event.Name() + " -> Connect");
276  return transit<Connect>();
277  }
278 };
279 
280 struct Disconnect : public sc::state<Disconnect, SandeshClientSMImpl> {
281  typedef mpl::list<
283  sc::custom_reaction<EvCollectorUpdate>,
287 
288  Disconnect(my_context ctx) : my_base(ctx) {
289  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
290  state_machine->set_state(SandeshClientSM::DISCONNECT);
291  SM_LOG(DEBUG, state_machine->StateName());
292  state_machine->SendUVE();
293  }
294 
295  sc::result react(const EvCollectorUpdate &event) {
296  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
297  state_machine->CollectorUpdate(event.collectors_);
298  // Update connection info
299  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
300  std::string(), ConnectionStatus::INIT,
301  state_machine->server(),
302  state_machine->StateName() + " : " + event.Name() +
303  " -> Connect");
304  return transit<Connect>();
305  }
306 };
307 
308 struct Connect : public sc::state<Connect, SandeshClientSMImpl> {
309  typedef mpl::list<
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>,
319 
320  static const int kConnectTimeout = 60; // seconds
321 
322  Connect(my_context ctx) : my_base(ctx) {
323  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
324  state_machine->set_state(SandeshClientSM::CONNECT);
325  StartSession(state_machine);
326  state_machine->connect_attempts_inc();
327  SM_LOG(DEBUG, state_machine->StateName() << " : " << "Start Connect timer " <<
328  state_machine->server());
329  state_machine->StartConnectTimer(state_machine->GetConnectTime());
330  state_machine->SendUVE();
331  }
332 
334  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
335  state_machine->CancelConnectTimer();
336  }
337 
338  sc::result react(const EvTcpConnectFail &event) {
339  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
340  SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name());
341  state_machine->CollectorChange();
342  return ToIdle(state_machine, event.Name());
343  }
344 
345 
346  sc::result react(const EvConnectTimerExpired &event) {
347  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
348  SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name());
349  state_machine->CollectorChange();
350  return ToIdle(state_machine, event.Name());
351  }
352 
353  sc::result react(const EvTcpConnected &event) {
354  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
355  SM_LOG(DEBUG, state_machine->StateName() << " : " <<
356  event.Name() << " : " << "Cancelling Connect timer");
357  state_machine->CancelConnectTimer();
358  SandeshSession *session = event.session;
359  // Update connection info
360  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
361  std::string(), ConnectionStatus::INIT, session->remote_endpoint(),
362  state_machine->StateName() + " : " + event.Name());
363  // Start the send queue runner XXX move this to Established or later
364  session->send_queue()->MayBeStartRunner();
365  return transit<ClientInit>();
366  }
367 
368  sc::result react(const EvTcpClose &event) {
369  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
370  SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name());
371  state_machine->CollectorChange();
372  return ToIdle(state_machine, event.Name());
373  }
374 
375  sc::result react(const EvCollectorUpdate &event) {
376  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
377  if (state_machine->CollectorUpdate(event.collectors_)) {
378  return ToIdle(state_machine, event.Name());
379  }
380  return discard_event();
381  }
382 
383  // Create an active connection request.
384  void StartSession(SandeshClientSMImpl *state_machine) {
385  SandeshSession *session = static_cast<SandeshSession *>(
386  state_machine->GetMgr()->CreateSMSession(
388  state_machine, _1, _2),
389  boost::bind(&SandeshClientSMImpl::OnMessage,
390  state_machine, _2, _1),
391  state_machine->server()));
392  session->set_stats_client(state_machine->GetMgr()->stats_client());
393  state_machine->set_session(session);
394  }
395 
396  sc::result ToIdle(SandeshClientSMImpl *state_machine,
397  const char *event_name) {
398  // Update connection info
399  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
400  std::string(), ConnectionStatus::DOWN,
401  state_machine->session()->remote_endpoint(),
402  state_machine->StateName() + " : " + event_name);
403  state_machine->set_idle_hold_time(state_machine->GetConnectTime() * 1000);
404  state_machine->OnIdle<EvStop>(EvStop());
405  state_machine->StartIdleHoldTimer();
406  return transit<Idle>();
407  }
408 };
409 
410 struct ClientInit : public sc::state<ClientInit, SandeshClientSMImpl> {
411  typedef mpl::list<
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>,
420 
421  ClientInit(my_context ctx) : my_base(ctx) {
422  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
423  state_machine->set_state(SandeshClientSM::CLIENT_INIT);
424  SM_LOG(DEBUG, state_machine->StateName());
425  state_machine->CancelConnectTimer();
426  state_machine->StartConnectTimer(state_machine->GetConnectTime());
427  state_machine->GetMgr()->InitializeSMSession(state_machine->connects_inc());
428  state_machine->SendUVE();
429  }
430 
432  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
433  state_machine->CancelConnectTimer();
434  }
435 
436  sc::result react(const EvTcpClose &event) {
437  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
438  SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name());
439  state_machine->CollectorChange();
440  return ToIdle(state_machine, event.Name());
441  }
442 
443  sc::result react(const EvConnectTimerExpired &event) {
444  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
445  SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name());
446  state_machine->CollectorChange();
447  return ToIdle(state_machine, event.Name());
448  }
449 
450  sc::result react(const EvSandeshMessageRecv &event) {
451  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
452  SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name());
453 
454  if (!state_machine->GetMgr()->ReceiveMsg(event.msg, event.header,
455  event.msg_type, event.header_offset)) {
456  return ToIdle(state_machine, event.Name());
457  }
458  state_machine->set_collector_name(event.header.get_Source());
459 
460  if (event.header.get_Hints() & g_sandesh_constants.SANDESH_CONTROL_HINT) {
461  // Update connection info
462  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
463  std::string(), ConnectionStatus::UP,
464  state_machine->session()->remote_endpoint(),
465  state_machine->StateName() + " : Control " + event.Name());
466  return transit<Established>();
467  }
468  return discard_event();
469  }
470 
471  sc::result react(const EvSandeshSend &event) {
472  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
473  Sandesh *snh(event.snh);
474  SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name() <<
475  " : " << snh->Name());
476  if (dynamic_cast<SandeshUVE *>(snh)) {
478  SANDESH_LOG(ERROR, "SANDESH: Send FAILED: " <<
479  snh->ToString());
480  }
482  SandeshTxDropReason::WrongClientSMState);
483  SM_LOG(INFO, "Received UVE message in wrong state : " << snh->Name());
484  snh->Release();
485  return discard_event();
486  }
487  if (!state_machine->send_session(snh)) {
488  SM_LOG(INFO, "Could not EnQ Sandesh :" << snh->Name());
489  // If Enqueue encounters an error, it will release the Sandesh
490  }
491  return discard_event();
492  }
493 
494  sc::result react(const EvCollectorUpdate &event) {
495  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
496  if (state_machine->CollectorUpdate(event.collectors_)) {
497  return ToIdle(state_machine, event.Name());
498  }
499  return discard_event();
500  }
501 
502  sc::result ToIdle(SandeshClientSMImpl *state_machine,
503  const char *event_name) {
504  // Update connection info
505  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
506  std::string(), ConnectionStatus::DOWN,
507  state_machine->session()->remote_endpoint(),
508  state_machine->StateName() + " : " + event_name);
509  state_machine->OnIdle<EvStop>(EvStop());
510  state_machine->StartIdleHoldTimer();
511  SM_LOG(INFO, "Return to idle with " << state_machine->idle_hold_time());
512  return transit<Idle>();
513  }
514 };
515 
516 struct Established : public sc::state<Established, SandeshClientSMImpl> {
517  typedef mpl::list<
519  sc::custom_reaction<EvTcpClose>,
520  sc::custom_reaction<EvSandeshMessageRecv>,
521  sc::custom_reaction<EvSandeshSend>,
522  sc::custom_reaction<EvCollectorUpdate>,
525 
526  Established(my_context ctx) : my_base(ctx) {
527  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
528  state_machine->set_state(SandeshClientSM::ESTABLISHED);
529  SM_LOG(DEBUG, state_machine->StateName());
530  state_machine->connect_attempts_clear();
531  // Update connection info
532  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
533  std::string(), ConnectionStatus::UP,
534  state_machine->session()->remote_endpoint(),
535  state_machine->StateName());
536  state_machine->SendUVE();
537  }
538 
540  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
541  state_machine->set_collector_name(string());
542  }
543 
544  sc::result react(const EvTcpClose &event) {
545  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
546  SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name());
547  if (state_machine->CollectorChange()) {
548  // Update connection info
549  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
550  std::string(), ConnectionStatus::INIT,
551  state_machine->session()->remote_endpoint(),
552  state_machine->StateName() + " : " + event.Name() +
553  " -> Connect");
554  state_machine->OnIdle<EvStop>(EvStop());
555  return transit<Connect>();
556  } else {
557  return ToIdle(state_machine, event.Name());
558  }
559  }
560 
561  sc::result react(const EvSandeshMessageRecv &event) {
562  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
563  SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name());
564 
565  if (!state_machine->GetMgr()->ReceiveMsg(event.msg, event.header,
566  event.msg_type, event.header_offset)) {
567  return ToIdle(state_machine, event.Name());
568  }
569  return discard_event();
570  }
571 
572  sc::result react(const EvSandeshSend &event) {
573  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
574  //SM_LOG(DEBUG, state_machine->StateName() << " : " << event.Name());
575  if (!state_machine->send_session(event.snh)) {
576  SM_LOG(ERROR, "Could not EnQ Sandesh :" << event.snh->Name());
577  // If Enqueue encounters an error, it will release the Sandesh
578  }
579  return discard_event();
580  }
581 
582  sc::result react(const EvCollectorUpdate &event) {
583  SandeshClientSMImpl *state_machine = &context<SandeshClientSMImpl>();
584  if (state_machine->CollectorUpdate(event.collectors_)) {
585  // Update connection info
586  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
587  std::string(), ConnectionStatus::INIT,
588  state_machine->session()->remote_endpoint(),
589  state_machine->StateName() + " : " + event.Name() +
590  " -> Connect");
591  state_machine->OnIdle<EvStop>(EvStop());
592  return transit<Connect>();
593  }
594  return discard_event();
595  }
596 
597  sc::result ToIdle(SandeshClientSMImpl *state_machine,
598  const char *event_name) {
599  // Update connection info
600  ConnectionState::GetInstance()->Update(ConnectionType::COLLECTOR,
601  std::string(), ConnectionStatus::DOWN,
602  state_machine->session()->remote_endpoint(),
603  state_machine->StateName() + " : " + event_name);
604  state_machine->OnIdle<EvStop>(EvStop());
605  state_machine->StartIdleHoldTimer();
606  return transit<Idle>();
607  }
608 
609 };
610 
611 } // namespace scm
612 
614  if (down) {
615  Enqueue(scm::EvStop());
616  } else {
617  reset_idle_hold_time();
618  // On fresh restart of state machine, all previous state should be reset
619  reset_last_info();
620  Enqueue(scm::EvStart());
621  }
622 }
623 
625  Enqueue(scm::EvTcpDeleteSession(session));
626 }
627 
628 template <class Ev>
629 void SandeshClientSMImpl::OnIdle(const Ev &event) {
630  // Release all resources
631  set_idle_hold_time(idle_hold_time() ? idle_hold_time() : kIdleHoldTime);
632 
633  CancelIdleHoldTimer();
634 
635  set_session(NULL, event.enq_);
636 }
637 
638 template <class Ev>
639 void SandeshClientSMImpl::ReleaseSandesh(const Ev &event) {
640  Sandesh *snh(event.snh);
642  SANDESH_LOG(ERROR, "SANDESH: Send FAILED: " << snh->ToString());
643  }
645  SandeshTxDropReason::WrongClientSMState);
646  SM_LOG(DEBUG, "Wrong state: " << StateName() << " for event: " <<
647  event.Name() << " message: " << snh->Name());
648  snh->Release();
649 }
650 
651 template <class Ev>
653  GetMgr()->DeleteSMSession(event.session);
654 }
655 
657  connect_timer_->Start(seconds * 1000,
658  boost::bind(&SandeshClientSMImpl::ConnectTimerExpired, this),
659  boost::bind(&SandeshClientSMImpl::TimerErrorHanlder, this, _1, _2));
660 }
661 
663  connect_timer_->Cancel();
664 }
665 
667  return connect_timer_->running();
668 }
669 
671  if (idle_hold_time_ <= 0)
672  return;
673 
674  idle_hold_timer_->Start(idle_hold_time_,
675  boost::bind(&SandeshClientSMImpl::IdleHoldTimerExpired, this),
676  boost::bind(&SandeshClientSMImpl::TimerErrorHanlder, this, _1, _2));
677 }
678 
680  idle_hold_timer_->Cancel();
681 }
682 
684  return idle_hold_timer_->running();
685 }
686 
687 //
688 // Test Only API : Start
689 //
691  connect_timer_->Fire();
692 }
693 
695  idle_hold_timer_->Fire();
696 }
697 //
698 // Test Only API : End
699 //
700 
701 void SandeshClientSMImpl::TimerErrorHanlder(std::string name, std::string error) {
702  SM_LOG(ERROR, name + " error: " + error);
703 }
704 
705 // Client only
707  if (!deleted_) {
708  SM_LOG(DEBUG, server() << " "
709  << "EvConnectTimerExpired in state " << StateName());
710  Enqueue(scm::EvConnectTimerExpired(connect_timer_));
711  }
712  return false;
713 }
714 
716  Enqueue(scm::EvIdleHoldTimerExpired(idle_hold_timer_));
717  return false;
718 }
719 
721  TcpSession *session, TcpSession::Event event) {
722  SandeshSession *sandesh_session = dynamic_cast<SandeshSession *>(session);
723  assert((session != NULL) == (sandesh_session != NULL));
724  std::string session_s = session ? session->ToString() : "*";
725  switch (event) {
727  SM_LOG(DEBUG, session_s << " " << __func__ <<
728  " " << "TCP Connected");
729  Enqueue(scm::EvTcpConnected(sandesh_session));
730  break;
732  SM_LOG(DEBUG, session_s << " " << __func__ <<
733  " " << "TCP Connect Failed");
734  Enqueue(scm::EvTcpConnectFail(sandesh_session));
735  break;
736  case TcpSession::CLOSE:
737  SM_LOG(DEBUG, session_s << " " << __func__ <<
738  " " << "TCP Connection Closed");
739  Enqueue(scm::EvTcpClose(sandesh_session));
740  break;
741  case TcpSession::ACCEPT:
742  default:
743  SM_LOG(DEBUG, session_s << " " << "Unknown event: " <<
744  event);
745  break;
746  }
747 }
748 
750  Enqueue(scm::EvSandeshSend(snh));
751  return true;
752 }
753 
755  Enqueue(scm::EvSandeshSend(snh));
756  return true;
757 }
758 
760  const std::string &msg) {
761  // Demux based on Sandesh message type
762  SandeshHeader header;
763  std::string message_type;
764  uint32_t xml_offset = 0;
765 
766  // Extract the header and message type
767  int ret = SandeshReader::ExtractMsgHeader(msg, header, message_type,
768  xml_offset);
769  if (ret) {
770  SM_LOG(ERROR, "OnMessage in state: " << StateName() << ": Extract "
771  << " FAILED(" << ret << ")");
772  return false;
773  }
774 
775  if (header.get_Hints() & g_sandesh_constants.SANDESH_CONTROL_HINT) {
776  SM_LOG(INFO, "OnMessage control in state: " << StateName() );
777  }
778  Enqueue(scm::EvSandeshMessageRecv(msg, header, message_type, xml_offset));
779  return true;
780 }
781 
782 static const std::string state_names[] = {
783  "Idle",
784  "Disconnect",
785  "Connect",
786  "ClientInit",
787  "Established",
788 };
789 
791  SandeshClientSM::State state) const {
792  return state_names[state];
793 }
794 
795 const string &SandeshClientSMImpl::StateName() const {
796  return state_names[state_];
797 }
798 
799 const string &SandeshClientSMImpl::LastStateName() const {
800  return state_names[last_state_];
801 }
802 
804 
806  int backoff = std::min(attempts_, 6);
807  return std::min(backoff ? 1 << (backoff - 1) : 0, kConnectInterval);
808 }
809 
810 void SandeshClientSMImpl::UpdateEventEnqueue(const sc::event_base &event) {
811  UpdateEventStats(event, true, false);
812 }
813 
814 void SandeshClientSMImpl::UpdateEventDequeue(const sc::event_base &event) {
815  UpdateEventStats(event, false, false);
816 }
817 
818 void SandeshClientSMImpl::UpdateEventEnqueueFail(const sc::event_base &event) {
819  UpdateEventStats(event, true, true);
820 }
821 
822 void SandeshClientSMImpl::UpdateEventDequeueFail(const sc::event_base &event) {
823  UpdateEventStats(event, false, true);
824 }
825 
826 void SandeshClientSMImpl::UpdateEventStats(const sc::event_base &event,
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);
831 }
832 
834  if (deleted_) return true;
835  in_dequeue_ = true;
836 
837  set_last_event(TYPE_NAME(*ec.event));
838  if (ec.validate.empty() || ec.validate(this)) {
839  if ((state()!=ESTABLISHED)||(TYPE_NAME(*ec.event)!="scm::EvSandeshSend"))
840  SM_LOG(DEBUG, "Processing " << TYPE_NAME(*ec.event) << " in state "
841  << StateName());
842  UpdateEventDequeue(*ec.event);
843  process_event(*ec.event);
844  } else {
845  SM_LOG(DEBUG, "Discarding " << TYPE_NAME(*ec.event) << " in state "
846  << StateName());
847  UpdateEventDequeueFail(*ec.event);
848  }
849 
850  ec.event.reset();
851  in_dequeue_ = false;
852  return true;
853 }
854 
855 void SandeshClientSMImpl::unconsumed_event(const sc::event_base &event) {
856  SM_LOG(DEBUG, "Unconsumed " << TYPE_NAME(event) << " in state "
857  << StateName());
858 }
859 
860 // This class determines whether a given class has a method called 'validate'
861 template<typename Ev>
862 struct HasValidate
863 {
864  template<typename T, bool (T::*)(SandeshClientSMImpl *) const> struct SFINAE {};
865  template<typename T> static char Test(SFINAE<T, &T::validate>*);
866  template<typename T> static int Test(...);
867  static const bool Has = sizeof(Test<Ev>(0)) == sizeof(char);
868 };
869 
870 template <typename Ev, bool has_validate>
871 struct ValidateFn {
872  EvValidate operator()(const Ev *event) { return NULL; }
873 };
874 
875 template <typename Ev>
876 struct ValidateFn<Ev, true> {
877  EvValidate operator()(const Ev *event) {
878  return boost::bind(&Ev::validate, event, _1);
879  }
880 };
881 
882 template <typename Ev>
883 void SandeshClientSMImpl::Enqueue(const Ev &event) {
884  if (deleted_) return;
885 
886  EventContainer ec;
887  ec.event = event.intrusive_from_this();
888  ec.validate = ValidateFn<Ev, HasValidate<Ev>::Has>()(static_cast<const Ev *>(ec.event.get()));
889  if (!work_queue_.Enqueue(ec)) {
890  // XXX - Disable till we implement bounded work queues
891  //UpdateEventEnqueueFail(event);
892  //return;
893  }
894  UpdateEventEnqueue(event);
895  return;
896 }
897 
898 
900  int sm_task_instance, int sm_task_id, bool periodicuve)
901  : SandeshClientSM(mgr),
902  work_queue_(sm_task_id, sm_task_instance,
903  boost::bind(&SandeshClientSMImpl::DequeueEvent, this, _1)),
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)),
907  idle_hold_time_(0),
908  statistics_timer_interval_(kTickInterval),
909  periodicuve_(periodicuve),
910  attempts_(0),
911  deleted_(false),
912  in_dequeue_(false),
913  connects_(0),
914  coll_name_(string()) {
915  state_ = IDLE;
916  generator_key_ = Sandesh::source() + ":" + Sandesh::node_type() + ":" +
918  initiate();
920 }
921 
923  std::scoped_lock lock(mutex_);
924 
925  assert(!deleted_);
926  deleted_ = true;
927 
928  //
929  // XXX Temporary hack until config task is made to run exclusively wrt
930  // all other threads including main()
931  //
932 
933  while (!work_queue_.IsQueueEmpty()) usleep(100);
934 
935  while (in_dequeue_) usleep(100);
936 
937  // The State Machine should have already been shutdown by this point.
938  assert(!session());
939 
941 
942  //
943  // Explicitly call the state destructor before the state machine itself.
944  // This is needed because some of the destructors access the state machine
945  // context.
946  //
947  terminate();
948 
949  //
950  // Delete timer after state machine is terminated so that there is no
951  // possible reference to the timers being deleted any more
952  //
955 
958 }
959 
963  boost::bind(&SandeshClientSMImpl::TimerErrorHanlder, this, _1,
964  _2));
965 }
966 
968  if (deleted_ || generator_key_.empty()) {
969  return true;
970  }
971  std::vector<SandeshStateMachineEvStats> ev_stats;
972  {
973  std::scoped_lock lock(mutex_);
974  event_stats_.Get(&ev_stats);
975  }
976  // Send the message
977  ModuleClientState mcs;
978  mcs.set_name(generator_key_);
979  mcs.set_sm_queue_count(work_queue_.Length());
980  mcs.set_max_sm_queue_count(work_queue_.max_queue_len());
981  // Sandesh state machine statistics
982  SandeshStateMachineStats sm_stats;
983  sm_stats.set_ev_stats(ev_stats);
984  sm_stats.set_state(StateName());
985  sm_stats.set_last_state(LastStateName());
986  sm_stats.set_last_event(last_event());
987  sm_stats.set_state_since(state_since_);
988  sm_stats.set_last_event_at(last_event_at_);
989  mcs.set_sm_stats(sm_stats);
990  // Sandesh session statistics
991  SandeshSession *session = this->session();
992  if (session) {
993  mcs.set_session_stats(session->GetStats());
994  SocketIOStats rx_stats;
995  session->GetRxSocketStats(rx_stats);
996  mcs.set_session_rx_socket_stats(rx_stats);
997  SocketIOStats tx_stats;
998  session->GetTxSocketStats(tx_stats);
999  mcs.set_session_tx_socket_stats(tx_stats);
1000  }
1001  SandeshModuleClientTrace::Send(mcs);
1002  SendUVE();
1003 
1004  map<string,uint32_t> inpMap;
1005  SandeshUVETypeMaps::SyncAllMaps(inpMap, true);
1006 
1007  return true;
1008 }
1009 
1011  const std::vector<TcpServer::Endpoint>& collectors) {
1012  Enqueue(scm::EvCollectorUpdate(collectors));
1013 }
1014 
1016  std::vector<TcpServer::Endpoint>& collectors) {
1017  collectors = collectors_;
1018 }
1019 
1021  if (collectors_.size()) {
1022  return collectors_[collector_index_];
1023  }
1024  return TcpServer::Endpoint();
1025 }
1026 
1028  if (collectors_.size()) {
1029  if (++collector_index_ == collectors_.size()) {
1030  collector_index_ = 0;
1031  }
1032  return collectors_[collector_index_];
1033  }
1034  return TcpServer::Endpoint();
1035 }
1036 
1038  const std::vector<TcpServer::Endpoint>& collectors) {
1039  collectors_ = collectors;
1040  collector_index_ = 0;
1041  TcpServer::Endpoint collector(GetCollector());
1042  if (server() != collector) {
1043  set_server(collector);
1044  SendUVE();
1045  return true;
1046  }
1047  SendUVE();
1048  return false;
1049 }
1050 
1053  if (server() != collector) {
1054  set_server(collector);
1055  SendUVE();
1056  return true;
1057  }
1058  return false;
1059 }
1060 
1062  EventManager *evm, Mgr *mgr, int sm_task_instance,
1063  int sm_task_id, bool periodicuve) {
1064  return new SandeshClientSMImpl(evm, mgr, sm_task_instance, sm_task_id, periodicuve);
1065 }
1066 
1067 
void GetCollectors(std::vector< TcpServer::Endpoint > &collectors)
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)
bool CollectorUpdate(const std::vector< TcpServer::Endpoint > &collectors)
void OnSessionEvent(TcpSession *session, TcpSession::Event event)
std::vector< TcpServer::Endpoint > collectors_
void Enqueue(const Ev &event)
void ReleaseSandesh(const Ev &event)
TcpServer::Endpoint GetNextCollector()
void EnqueDelSession(SandeshSession *session)
const std::string last_event() const
void SetAdminState(bool down)
void DeleteTcpSession(const Ev &event)
bool OnMessage(SandeshSession *session, const std::string &msg)
void StartConnectTimer(int seconds)
bool SendSandeshUVE(Sandesh *snh)
void SetCollectors(const std::vector< TcpServer::Endpoint > &collectors)
WorkQueue< EventContainer > work_queue_
TcpServer::Endpoint GetCollector() const
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)
bool DequeueEvent(EventContainer ec)
void set_state(State state)
const std::string & LastStateName() const
static const int kConnectInterval
void OnIdle(const Ev &event)
const std::string & StateName() const
void unconsumed_event(const sc::event_base &event)
void UpdateEventEnqueue(const sc::event_base &event)
void set_collector_name(const std::string &cname)
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)
Definition: sandesh_uve.cc:61
static void UpdateTxMsgFailStats(const std::string &msg_name, uint64_t bytes, SandeshTxDropReason::type dreason)
Definition: sandesh.cc:892
virtual void Release()
Definition: cpp/sandesh.h:269
static std::string source()
Definition: cpp/sandesh.h:292
virtual const char * Name() const
Definition: cpp/sandesh.h:280
SandeshType::type type() const
Definition: cpp/sandesh.h:317
static bool IsLoggingDroppedAllowed(SandeshType::type)
Definition: sandesh.cc:846
static std::string module()
Definition: cpp/sandesh.h:294
static std::string instance_id()
Definition: cpp/sandesh.h:296
static std::string node_type()
Definition: cpp/sandesh.h:298
virtual std::string ToString() const =0
boost::asio::ip::tcp::endpoint Endpoint
Definition: tcp_server.h:31
@ CONNECT_COMPLETE
Definition: tcp_session.h:47
@ CONNECT_FAILED
Definition: tcp_session.h:48
virtual std::string ToString() const
Definition: tcp_session.h:80
void GetRxSocketStats(SocketIOStats *socket_stats) const
Definition: tcp_session.cc:914
Endpoint remote_endpoint() const
Definition: tcp_session.h:132
void GetTxSocketStats(SocketIOStats *socket_stats) const
Definition: tcp_session.cc:918
static bool DeleteTimer(Timer *Timer)
Definition: timer.cc:222
Definition: timer.h:58
bool Cancel()
Definition: timer.cc:150
bool Start(int time, Handler handler, ErrorHandler error_handler=NULL)
Definition: timer.cc:108
size_t Length() const
Definition: queue_task.h:357
void Shutdown(bool delete_entries=true)
Definition: queue_task.h:153
size_t max_queue_len() const
Definition: queue_task.h:378
bool IsQueueEmpty() const
Definition: queue_task.h:353
void MayBeStartRunner()
Definition: queue_task.h:282
static EventManager evm
#define SANDESH_LOG(_Level, _Msg)
Definition: cpp/sandesh.h:477
#define TYPE_NAME(_type)
Definition: logging.h:33
#define SM_LOG(_Level, _Msg)
#define SESSION_LOG(session)
static const std::string state_names[]
boost::function< bool(StateMachine *)> EvValidate
Definition: state_machine.h:34
static char Test(SFINAE< T, &T::validate > *)
static int Test(...)
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)
Connect(my_context ctx)
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()
static const char * Name()
static const char * Name()
EvSandeshMessageRecv(const std::string &msg, const SandeshHeader &header, const std::string &msg_type, const uint32_t &header_offset)
const SandeshHeader header
EvSandeshSend(Sandesh *snh)
static const char * Name()
static const char * Name()
EvStop(bool enq)
static const char * Name()
static const char * Name()
SandeshSession * session
EvTcpClose(SandeshSession *session)
static const char * Name()
EvTcpConnectFail(SandeshSession *session)
SandeshSession * session
static const char * Name()
EvTcpConnected(SandeshSession *session)
SandeshSession * session
static const char * Name()
EvTcpDeleteSession(SandeshSession *session)
sc::result react(const EvCollectorUpdate &event)
sc::result react(const EvStop &event)
Idle(my_context ctx)
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