OpenSDN source code
bgp_xmpp_channel.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 #include "bgp/bgp_xmpp_channel.h"
7 
8 #include <boost/assign/list_of.hpp>
9 #include <boost/foreach.hpp>
10 
11 #include <limits>
12 #include <sstream>
13 #include <vector>
14 #include <atomic>
15 
16 #include "base/regex.h"
17 #include "base/task_annotations.h"
18 #include "bgp/bgp_config.h"
19 #include "bgp/bgp_factory.h"
20 #include "bgp/bgp_log.h"
21 #include "bgp/bgp_membership.h"
22 #include "bgp/bgp_server.h"
23 #include "bgp/bgp_update_sender.h"
25 #include "bgp/inet/inet_table.h"
26 #include "bgp/inet6/inet6_table.h"
35 #include "bgp/evpn/evpn_route.h"
36 #include "bgp/evpn/evpn_table.h"
37 #include "bgp/mvpn/mvpn_table.h"
38 #include "bgp/peer_close_manager.h"
39 #include "bgp/peer_stats.h"
43 #include "control-node/sandesh/control_node_types.h"
44 #include "net/community_type.h"
45 #include "schema/xmpp_multicast_types.h"
46 #include "schema/xmpp_enet_types.h"
47 #include "schema/xmpp_mvpn_types.h"
48 #include "xml/xml_pugi.h"
49 #include "xmpp/xmpp_connection.h"
50 #include "xmpp/xmpp_init.h"
51 #include "xmpp/xmpp_server.h"
52 #include "xmpp/sandesh/xmpp_peer_info_types.h"
53 
54 using autogen::EnetItemType;
55 using autogen::EnetNextHopListType;
56 using autogen::EnetSecurityGroupListType;
57 using autogen::EnetTunnelEncapsulationListType;
58 
59 using autogen::McastItemType;
60 using autogen::McastNextHopsType;
61 using autogen::McastTunnelEncapsulationListType;
62 
63 using autogen::MvpnItemType;
64 using autogen::MvpnNextHopType;
65 using autogen::MvpnTunnelEncapsulationListType;
66 
67 using autogen::ItemType;
68 using autogen::NextHopListType;
69 using autogen::SecurityGroupListType;
70 using autogen::CommunityTagListType;
71 using autogen::TunnelEncapsulationListType;
72 using autogen::TagListType;
73 
74 using boost::assign::list_of;
75 using boost::smatch;
76 using boost::system::error_code;
77 using contrail::regex;
80 using pugi::xml_node;
81 using std::unique_ptr;
82 using std::make_pair;
83 using std::numeric_limits;
84 using std::ostringstream;
85 using std::pair;
86 using std::set;
87 using std::string;
88 using std::vector;
89 
90 //
91 // Calculate med from local preference.
92 // Should move agent definitions to a common location and use those here
93 // instead of hard coded values.
94 //
95 static uint32_t GetMedFromLocalPref(uint32_t local_pref) {
96  if (local_pref == 0)
97  return 0;
98  if (local_pref == 100)
99  return 200;
100  if (local_pref == 200)
101  return 100;
102  return numeric_limits<uint32_t>::max() - local_pref;
103 }
104 
107 }
108 
110  ++inet6_rx_bad_prefix_count;
111 }
112 
114  ++inet6_rx_bad_nexthop_count;
115 }
116 
118  ++inet6_rx_bad_afi_safi_count;
119 }
120 
122  return inet6_rx_bad_xml_token_count;
123 }
124 
126  return inet6_rx_bad_prefix_count;
127 }
128 
130  return inet6_rx_bad_nexthop_count;
131 }
132 
134  return inet6_rx_bad_afi_safi_count;
135 }
136 
138 public:
139  explicit PeerStats(BgpXmppChannel *peer)
140  : parent_(peer) {
141  }
142 
143  // Used when peer flaps.
144  // Don't need to do anything since the BgpXmppChannel itself gets deleted.
145  virtual void Clear() {
146  }
147 
148  // Printable name
149  virtual string ToString() const {
150  return parent_->ToString();
151  }
152 
153  // Previous State of the peer
154  virtual string last_state() const {
155  return (parent_->channel_->LastStateName());
156  }
157  // Last state change occurred at
158  virtual string last_state_change_at() const {
159  return (parent_->channel_->LastStateChangeAt());
160  }
161 
162  // Last error on this peer
163  virtual string last_error() const {
164  return "";
165  }
166 
167  // Last Event on this peer
168  virtual string last_event() const {
169  return (parent_->channel_->LastEvent());
170  }
171 
172  // When was the Last
173  virtual string last_flap() const {
174  return (parent_->channel_->LastFlap());
175  }
176 
177  // Total number of flaps
178  virtual uint64_t num_flaps() const {
179  return (parent_->channel_->FlapCount());
180  }
181 
182  virtual void GetRxProtoStats(ProtoStats *stats) const {
183  stats->open = parent_->channel_->rx_open();
184  stats->close = parent_->channel_->rx_close();
185  stats->keepalive = parent_->channel_->rx_keepalive();
186  stats->update = parent_->channel_->rx_update();
187  }
188 
189  virtual void GetTxProtoStats(ProtoStats *stats) const {
190  stats->open = parent_->channel_->tx_open();
191  stats->close = parent_->channel_->tx_close();
192  stats->keepalive = parent_->channel_->tx_keepalive();
193  stats->update = parent_->channel_->tx_update();
194  }
195 
196  virtual void GetRxRouteUpdateStats(UpdateStats *stats) const {
197  stats->reach = parent_->stats_[RX].reach.load();
198  stats->unreach = parent_->stats_[RX].unreach.load();
199  stats->end_of_rib = parent_->stats_[RX].end_of_rib.load();
200  stats->total = stats->reach + stats->unreach + stats->end_of_rib;
201  }
202 
203  virtual void GetTxRouteUpdateStats(UpdateStats *stats) const {
204  stats->reach = parent_->stats_[TX].reach.load();
205  stats->unreach = parent_->stats_[TX].unreach.load();
206  stats->end_of_rib = parent_->stats_[TX].end_of_rib.load();
207  stats->total = stats->reach + stats->unreach + stats->end_of_rib;
208  }
209 
210  virtual void GetRxSocketStats(IPeerDebugStats::SocketStats *stats) const {
211  const XmppSession *session = parent_->GetSession();
212  if (session) {
213  const io::SocketStats &socket_stats = session->GetSocketStats();
214  stats->calls = socket_stats.read_calls;
215  stats->bytes = socket_stats.read_bytes;
216  }
217  }
218 
219  virtual void GetTxSocketStats(IPeerDebugStats::SocketStats *stats) const {
220  const XmppSession *session = parent_->GetSession();
221  if (session) {
222  const io::SocketStats &socket_stats = session->GetSocketStats();
223  stats->calls = socket_stats.write_calls;
224  stats->bytes = socket_stats.write_bytes;
225  stats->blocked_count = socket_stats.write_blocked;
226  stats->blocked_duration_usecs =
227  socket_stats.write_blocked_duration_usecs;
228  }
229  }
230 
231  virtual void GetRxErrorStats(RxErrorStats *stats) const {
232  const BgpXmppChannel::ErrorStats &err_stats = parent_->error_stats();
235  stats->inet6_bad_prefix_count =
236  err_stats.get_inet6_rx_bad_prefix_count();
237  stats->inet6_bad_nexthop_count =
238  err_stats.get_inet6_rx_bad_nexthop_count();
239  stats->inet6_bad_afi_safi_count =
241  }
242 
243  virtual void GetRxRouteStats(RxRouteStats *stats) const {
246  }
247 
248  virtual void UpdateTxUnreachRoute(uint64_t count) {
249  parent_->stats_[TX].unreach += count;
250  }
251 
252  virtual void UpdateTxReachRoute(uint64_t count) {
253  parent_->stats_[TX].reach += count;
254  }
255 
256 private:
258 };
259 
261 public:
263  : server_(server),
264  parent_(channel),
265  is_closed_(false),
266  send_ready_(true),
267  closed_at_(0) {
268  total_path_count_ = 0;
270  }
271 
272  virtual ~XmppPeer() {
273  assert(GetTotalPathCount() == 0);
274 
275  XmppPeerInfoData peer_info;
276  peer_info.set_name(ToUVEKey());
277  peer_info.set_deleted(true);
278  parent_->XMPPPeerInfoSend(peer_info);
279 
280  PeerStatsData peer_stats_data;
281  peer_stats_data.set_name(ToUVEKey());
282  peer_stats_data.set_deleted(true);
283  assert(!peer_stats_data.get_name().empty());
284  BGP_UVE_SEND2(PeerStatsUve, peer_stats_data, "ObjectXmppPeerInfo");
285  }
286 
288  BgpPath *path) {
289  if (parent_->close_manager_->IsMembershipInUse())
290  return parent_->close_manager_->MembershipPathCallback(tpart, rt,
291  path);
292 
293  BgpTable *table = static_cast<BgpTable *>(tpart->parent());
294  return table->DeletePath(tpart, rt, path);
295  }
296 
297  virtual bool SendUpdate(const uint8_t *msg, size_t msgsize,
298  const std::string *msg_str);
299  virtual bool SendUpdate(const uint8_t *msg, size_t msgsize) {
300  return SendUpdate(msg, msgsize, NULL);
301  }
302  virtual const string &ToString() const {
303  return parent_->ToString();
304  }
305 
306  virtual bool CanUseMembershipManager() const {
307  return parent_->GetMembershipRequestQueueSize() == 0;
308  }
309 
310  virtual bool IsRegistrationRequired() const { return true; }
311 
312  virtual const string &ToUVEKey() const {
313  return parent_->ToUVEKey();
314  }
315 
316  virtual BgpServer *server() { return server_; }
317  virtual BgpServer *server() const { return server_; }
318  virtual IPeerClose *peer_close() {
319  return parent_->peer_close_.get();
320  }
321  virtual IPeerClose *peer_close() const {
322  return parent_->peer_close_.get();
323  }
324 
325  void UpdateCloseRouteStats(Address::Family family, const BgpPath *old_path,
326  uint32_t path_flags) const {
327  peer_close()->UpdateRouteStats(family, old_path, path_flags);
328  }
329 
331  return parent_->peer_stats_.get();
332  }
333  virtual const IPeerDebugStats *peer_stats() const {
334  return parent_->peer_stats_.get();
335  }
336 
337  virtual bool IsReady() const {
338  return (parent_->channel_->GetPeerState() == xmps::READY);
339  }
340  virtual const string GetStateName() const {
341  switch (parent_->channel_->GetPeerState()) {
342  case xmps::UNKNOWN: return "UNKNOWN";
343  case xmps::READY: return "READY";
344  case xmps::NOT_READY: return "NOT_READY";
345  case xmps::TIMEDOUT: return "TIMEDOUT";
346  }
347  return "UNKNOWN";
348  }
349  virtual bool IsXmppPeer() const {
350  return true;
351  }
352  virtual void Close(bool graceful);
353 
354  const bool IsDeleted() const { return is_closed_; }
355  void SetPeerClosed(bool closed) {
356  is_closed_ = closed;
357  if (is_closed_)
359  }
360  uint64_t closed_at() const { return closed_at_; }
361 
362  virtual BgpProto::BgpPeerType PeerType() const {
363  return BgpProto::XMPP;
364  }
365 
366  virtual uint32_t bgp_identifier() const {
367  const TcpSession::Endpoint &remote = parent_->endpoint();
368  if (remote.address().is_v4()) {
369  return remote.address().to_v4().to_ulong();
370  }
371  return 0;
372  }
373 
374  virtual void UpdateTotalPathCount(int count) const {
375  total_path_count_ += count;
376  }
377  virtual int GetTotalPathCount() const {
378  return total_path_count_;
379  }
380  virtual bool IsAs4Supported() const { return true; }
381  virtual void UpdatePrimaryPathCount(int count,
382  Address::Family family) const {
383  primary_path_count_ += count;
384  }
385  virtual int GetPrimaryPathCount() const {
386  return primary_path_count_;
387  }
388  virtual void ProcessPathTunnelEncapsulation(const BgpPath *path,
389  BgpAttr *attr, ExtCommunityDB *extcomm_db, const BgpTable *table)
390  const {
391  }
392  virtual const std::vector<std::string> GetDefaultTunnelEncap(
393  Address::Family family) const {
394  return std::vector<std::string>();
395  }
396  virtual bool IsInGRTimerWaitState() const {
397  return parent_->close_manager_->IsInGRTimerWaitState();
398  }
399 
402  }
403 
404  virtual bool send_ready() const { return send_ready_; }
405  bool IsRouterTypeBGPaaS() const { return false; }
406 
407 private:
408  void WriteReadyCb(const boost::system::error_code &ec) {
409  if (!server_) return;
411  BGP_LOG_PEER(Event, this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_ALL,
412  BGP_PEER_DIR_NA, "Send ready");
413  sender->PeerSendReady(this);
414  send_ready_ = true;
415 
416  // Restart EndOfRib Send timer if necessary.
418  }
419 
422  mutable std::atomic<int> total_path_count_;
423  mutable std::atomic<int> primary_path_count_;
426  uint64_t closed_at_;
427 };
428 
429 // Skip sending updates if the destinatin matches against the pattern.
430 // XXX Used in test environments only
432  static char *skip_env_ = getenv("XMPP_SKIP_UPDATE_SEND");
433  if (!skip_env_)
434  return false;
435 
436  // Use XMPP_SKIP_UPDATE_SEND as a regex pattern to match against destination
437  // Cache the result to avoid redundant regex evaluation
439  smatch matches;
440  skip_update_send_ = regex_search(ToString(), matches, regex(skip_env_));
442  }
443  return skip_update_send_;
444 }
445 
446 bool BgpXmppChannel::XmppPeer::SendUpdate(const uint8_t *msg, size_t msgsize,
447  const string *msg_str) {
448  XmppChannel *channel = parent_->channel_;
449  if (channel->GetPeerState() == xmps::READY) {
450  parent_->stats_[TX].rt_updates++;
451  if (parent_->SkipUpdateSend())
452  return true;
453  send_ready_ = channel->Send(msg, msgsize, msg_str, xmps::BGP,
454  boost::bind(&BgpXmppChannel::XmppPeer::WriteReadyCb, this, _1));
455  if (!send_ready_) {
456  BGP_LOG_PEER(Event, this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_ALL,
457  BGP_PEER_DIR_NA, "Send blocked");
458 
459  // If EndOfRib Send timer is running, cancel it and reschedule it
460  // after socket gets unblocked.
461  if (parent_->eor_send_timer_ && parent_->eor_send_timer_->running())
462  parent_->eor_send_timer_->Cancel();
463  }
464  return send_ready_;
465  } else {
466  return false;
467  }
468 }
469 
470 void BgpXmppChannel::XmppPeer::Close(bool graceful) {
471  send_ready_ = true;
472  parent_->set_peer_closed(true);
473  if (server_ == NULL)
474  return;
475 
476  XmppConnection *connection =
477  const_cast<XmppConnection *>(parent_->channel_->connection());
478 
479  if (connection && !connection->IsActiveChannel()) {
480 
481  // Clear EOR state.
482  parent_->ClearEndOfRibState();
483 
484  parent_->peer_close_->Close(graceful);
485  }
486 }
487 
491  : channel_(channel),
492  peer_id_(xmps::BGP),
495  peer_(new XmppPeer(bgp_server, this)),
496  peer_close_(new BgpXmppPeerClose(this)),
497  peer_stats_(new PeerStats(this)),
498  bgp_policy_(BgpProto::XMPP, RibExportPolicy::XMPP, -1, 0),
499  manager_(manager),
500  delete_in_progress_(false),
501  deleted_(false),
502  defer_peer_close_(false),
503  skip_update_send_(false),
505  eor_sent_(false),
506  eor_receive_timer_(NULL),
507  eor_send_timer_(NULL),
511  TaskScheduler::GetInstance()->GetTaskId("xmpp::StateMachine"),
512  channel->GetTaskInstance(),
513  boost::bind(&BgpXmppChannel::MembershipResponseHandler, this, _1)),
514  lb_mgr_(new LabelBlockManager()) {
515  close_manager_.reset(
516  BgpStaticObjectFactory::Create<PeerCloseManager>(static_cast<IPeerClose*>(peer_close_.get())));
517  if (bgp_server) {
520  "EndOfRib receive timer",
521  TaskScheduler::GetInstance()->GetTaskId("xmpp::StateMachine"),
525  "EndOfRib send timer",
526  TaskScheduler::GetInstance()->GetTaskId("xmpp::StateMachine"),
528  }
531  boost::bind(&BgpXmppChannel::ReceiveUpdate, this, _1));
532  BGP_LOG_PEER(Event, peer_.get(), SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
533  BGP_PEER_DIR_NA, "Created");
534 }
535 
538  CHECK_CONCURRENCY("bgp::Config");
539  }
540 
541  if (manager_)
546  assert(peer_deleted());
547  assert(!close_manager_->IsMembershipInUse());
548  assert(table_membership_request_map_.empty());
551  BGP_LOG_PEER(Event, peer_.get(), SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
552  BGP_PEER_DIR_NA, "Deleted");
556 }
557 
558 void BgpXmppChannel::XMPPPeerInfoSend(const XmppPeerInfoData &peer_info) const {
559  assert(!peer_info.get_name().empty());
560  BGP_UVE_SEND(XMPPPeerInfo, peer_info);
561 }
562 
564  if (channel_ && channel_->connection()) {
565  return channel_->connection()->session();
566  }
567  return NULL;
568 }
569 
570 const string &BgpXmppChannel::ToString() const {
571  return channel_->ToString();
572 }
573 
574 const string &BgpXmppChannel::ToUVEKey() const {
575  if (channel_->connection()) {
576  return channel_->connection()->ToUVEKey();
577  } else {
578  return channel_->ToString();
579  }
580 }
581 
583  return channel_->StateName();
584 }
585 
586 
588  return table_membership_request_map_.size();
589 }
590 
591 void BgpXmppChannel::RoutingInstanceCallback(string vrf_name, int op) {
593  return;
594  if (vrf_name == BgpConfigManager::kMasterInstance)
595  return;
597  return;
598 
600  assert(instance_mgr);
601  RoutingInstance *rt_instance = instance_mgr->GetRoutingInstance(vrf_name);
602  assert(rt_instance);
603 
605  const InstanceMembershipRequestState *imr_state =
606  GetInstanceMembershipState(vrf_name);
607  if (!imr_state)
608  return;
609  ProcessDeferredSubscribeRequest(rt_instance, *imr_state);
611  } else {
612  SubscriptionState *sub_state = GetSubscriptionState(rt_instance);
613  if (!sub_state)
614  return;
615  rtarget_manager_->RoutingInstanceCallback(
616  rt_instance, &sub_state->targets);
617  }
618 }
619 
621  return peer_.get();
622 }
623 
624 const IPeer *BgpXmppChannel::Peer() const {
625  return peer_.get();
626 }
627 
629  return channel_->connection()->endpoint();
630 }
631 
632 bool BgpXmppChannel::XmppDecodeAddress(int af, const string &address,
633  IpAddress *addrp, bool zero_ok) {
634  if (af != BgpAf::IPv4 && af != BgpAf::IPv6 && af != BgpAf::L2Vpn)
635  return false;
636 
637  error_code error;
638  *addrp = IpAddress::from_string(address, error);
639  if (error)
640  return false;
641 
642  return (zero_ok ? true : !addrp->is_unspecified());
643 }
644 
645 //
646 // Return true if there's a pending request, false otherwise.
647 //
649  int *instance_id, uint64_t *subscription_gen_id, RequestType *req_type) {
650  *instance_id = -1;
651  *subscription_gen_id = 0;
652  TableMembershipRequestState *tmr_state =
653  GetTableMembershipState(table->name());
654  if (tmr_state) {
655  *req_type = tmr_state->pending_req;
656  *instance_id = tmr_state->instance_id;
657  return true;
658  } else {
659  *req_type = NONE;
661  mgr->GetRegistrationInfo(peer_.get(), table,
662  instance_id, subscription_gen_id);
663  return false;
664  }
665 }
666 
667 //
668 // Add entry to the pending table request map.
669 //
670 void BgpXmppChannel::AddTableMembershipState(const string &table_name,
671  TableMembershipRequestState tmr_state) {
672  table_membership_request_map_.insert(make_pair(table_name, tmr_state));
673 }
674 
675 //
676 // Delete entry from the pending table request map.
677 // Return true if the entry was found and deleted.
678 //
679 bool BgpXmppChannel::DeleteTableMembershipState(const string &table_name) {
680  return (table_membership_request_map_.erase(table_name) > 0);
681 }
682 
683 //
684 // Find entry in the pending table request map.
685 //
688  const string &table_name) {
689  TableMembershipRequestMap::iterator loc =
690  table_membership_request_map_.find(table_name);
691  return (loc == table_membership_request_map_.end() ? NULL : &loc->second);
692 }
693 
694 //
695 // Find entry in the pending table request map.
696 // Const version.
697 //
700  const string &table_name) const {
701  TableMembershipRequestMap::const_iterator loc =
702  table_membership_request_map_.find(table_name);
703  return (loc == table_membership_request_map_.end() ? NULL : &loc->second);
704 }
705 
706 //
707 // Add entry to the pending instance request map.
708 //
709 void BgpXmppChannel::AddInstanceMembershipState(const string &instance,
710  InstanceMembershipRequestState imr_state) {
711  instance_membership_request_map_.insert(make_pair(instance, imr_state));
712 }
713 
714 //
715 // Delete entry from the pending instance request map.
716 // Return true if the entry was found and deleted.
717 //
718 bool BgpXmppChannel::DeleteInstanceMembershipState(const string &instance) {
719  return (instance_membership_request_map_.erase(instance) > 0);
720 }
721 
722 //
723 // Find the entry in the pending instance request map.
724 //
726 BgpXmppChannel::GetInstanceMembershipState(const string &instance) const {
727  InstanceMembershipRequestMap::const_iterator loc =
728  instance_membership_request_map_.find(instance);
729  return loc != instance_membership_request_map_.end() ? &loc->second : NULL;
730 }
731 
732 //
733 // Verify that there's a subscribe or pending subscribe for the table
734 // corresponding to the vrf and family.
735 // If there's a subscribe, populate the table and instance_id.
736 // If there's a pending subscribe, populate the instance_id.
737 // The subscribe_pending parameter is set appropriately.
738 //
739 // Return true if there's a subscribe or pending subscribe, false otherwise.
740 //
741 bool BgpXmppChannel::VerifyMembership(const string &vrf_name,
742  Address::Family family, BgpTable **table,
743  int *instance_id, uint64_t *subscription_gen_id, bool *subscribe_pending,
744  bool add_change) {
745  *table = NULL;
746  *subscribe_pending = false;
747 
749  RoutingInstance *rt_instance = instance_mgr->GetRoutingInstance(vrf_name);
750  if (rt_instance)
751  *table = rt_instance->GetTable(family);
752  if (rt_instance != NULL && !rt_instance->deleted()) {
753  RequestType req_type;
754  if (GetMembershipInfo(*table, instance_id,
755  subscription_gen_id, &req_type)) {
756  // Bail if there's a pending unsubscribe.
757  if (req_type != SUBSCRIBE) {
760  "Received route after unsubscribe");
761  return false;
762  }
763  *subscribe_pending = true;
764  } else {
765  // Bail if we are not subscribed to the table.
766  if (*instance_id < 0) {
769  "Received route without subscribe");
770  return false;
771  }
772  }
773  } else {
774  // Bail if there's no pending subscribe for the instance.
775  // Note that route retract can be received while the instance is
776  // marked for deletion.
777  const InstanceMembershipRequestState *imr_state =
778  GetInstanceMembershipState(vrf_name);
779  if (imr_state) {
780  *instance_id = imr_state->instance_id;
781  *subscribe_pending = true;
782  } else if (add_change || !rt_instance) {
784  BGP_LOG_FLAG_ALL, "Received route without pending subscribe");
785  return false;
786  }
787  }
788 
789  return true;
790 }
791 
792 bool BgpXmppChannel::ProcessMcastItem(string vrf_name,
793  const pugi::xml_node &node, bool add_change) {
794  McastItemType item;
795  item.Clear();
796 
797  if (!item.XmlParse(node)) {
799  BGP_LOG_FLAG_ALL, "Invalid multicast route message received");
800  return false;
801  }
802 
803  if (item.entry.nlri.af != BgpAf::IPv4) {
805  "Unsupported address family " << item.entry.nlri.af <<
806  " for multicast route");
807  return false;
808  }
809 
810  if (item.entry.nlri.safi != BgpAf::Mcast) {
812  BGP_LOG_FLAG_ALL, "Unsupported subsequent address family " <<
813  item.entry.nlri.safi << " for multicast route");
814  return false;
815  }
816 
817  error_code error;
818  IpAddress grp_address = IpAddress::from_string("0.0.0.0", error);
819  if (!item.entry.nlri.group.empty()) {
820  if (!XmppDecodeAddress(item.entry.nlri.af,
821  item.entry.nlri.group, &grp_address, false)) {
823  "Bad group address " << item.entry.nlri.group);
824  return false;
825  }
826  }
827 
828  IpAddress src_address = IpAddress::from_string("0.0.0.0", error);
829  if (!item.entry.nlri.source.empty()) {
830  if (!XmppDecodeAddress(item.entry.nlri.af,
831  item.entry.nlri.source, &src_address, true)) {
833  "Bad source address " << item.entry.nlri.source);
834  return false;
835  }
836  }
837 
838  bool subscribe_pending;
839  int instance_id;
840  uint64_t subscription_gen_id;
841  BgpTable *table;
842  if (!VerifyMembership(vrf_name, Address::ERMVPN, &table, &instance_id,
843  &subscription_gen_id, &subscribe_pending, add_change)) {
844  channel_->Close();
845  return false;
846  }
847 
848  // Build the key to the Multicast DBTable
849  uint16_t cluster_seed =
851  RouteDistinguisher mc_rd;
852  if (cluster_seed) {
853  mc_rd = RouteDistinguisher(cluster_seed, peer_->bgp_identifier(),
854  instance_id);
855  } else {
856  mc_rd = RouteDistinguisher(peer_->bgp_identifier(), instance_id);
857  }
858 
859  ErmVpnPrefix mc_prefix(ErmVpnPrefix::NativeRoute, mc_rd,
860  grp_address.to_v4(), src_address.to_v4());
861 
862  // Build and enqueue a DB request for route-addition
863  DBRequest req;
864  req.key.reset(new ErmVpnTable::RequestKey(mc_prefix, peer_.get()));
865 
866  uint32_t flags = 0;
867  ExtCommunitySpec ext;
868  string label_range("none");
869 
870  if (add_change) {
872  vector<uint32_t> labels;
873  const McastNextHopsType &inh_list = item.entry.next_hops;
874 
875  if (inh_list.next_hop.empty()) {
877  BGP_LOG_FLAG_ALL, "Missing next-hop for multicast route " <<
878  mc_prefix.ToString());
879  return false;
880  }
881 
882  // Agents should send only one next-hop in the item
883  if (inh_list.next_hop.size() != 1) {
885  "More than one nexthop received for multicast route " <<
886  mc_prefix.ToString());
887  return false;
888  }
889 
890  McastNextHopsType::const_iterator nit = inh_list.begin();
891 
892  // Label Allocation item.entry.label by parsing the range
893  label_range = nit->label;
894  if (!stringToIntegerList(label_range, "-", labels) ||
895  labels.size() != 2) {
897  "Bad label range " << label_range <<
898  " for multicast route " << mc_prefix.ToString());
899  return false;
900  }
901 
902  if (!labels[0] || !labels[1] || labels[1] < labels[0]) {
904  BGP_LOG_FLAG_ALL, "Bad label range " << label_range <<
905  " for multicast route " << mc_prefix.ToString());
906  return false;
907  }
908 
909  BgpAttrSpec attrs;
910  LabelBlockPtr lbptr = lb_mgr_->LocateBlock(labels[0], labels[1]);
911 
912  BgpAttrLabelBlock attr_label(lbptr);
913  attrs.push_back(&attr_label);
914 
915  // Next-hop ip address
916  IpAddress nh_address;
917  if (!XmppDecodeAddress(nit->af, nit->address, &nh_address)) {
919  BGP_LOG_FLAG_ALL, "Bad nexthop address " << nit->address <<
920  " for multicast route " << mc_prefix.ToString());
921  return false;
922  }
923  BgpAttrNextHop nexthop(nh_address.to_v4().to_ulong());
924  attrs.push_back(&nexthop);
925 
926  // Process tunnel encapsulation list.
927  bool no_tunnel_encap = true;
928  bool no_valid_tunnel_encap = true;
929  for (McastTunnelEncapsulationListType::const_iterator eit =
930  nit->tunnel_encapsulation_list.begin();
931  eit != nit->tunnel_encapsulation_list.end(); ++eit) {
932  no_tunnel_encap = false;
933  TunnelEncap tun_encap(*eit);
934  if (tun_encap.tunnel_encap() == TunnelEncapType::UNSPEC)
935  continue;
936  no_valid_tunnel_encap = false;
937  ext.communities.push_back(tun_encap.GetExtCommunityValue());
938  }
939 
940  // Mark the path as infeasible if all tunnel encaps published
941  // by agent are invalid.
942  if (!no_tunnel_encap && no_valid_tunnel_encap) {
943  flags = BgpPath::NoTunnelEncap;
944  }
945 
946  if (!ext.communities.empty())
947  attrs.push_back(&ext);
948 
949  BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attrs);
950  req.data.reset(new ErmVpnTable::RequestData(
951  attr, flags, 0, 0, subscription_gen_id));
952  stats_[RX].reach++;
953  } else {
955  stats_[RX].unreach++;
956  }
957 
958  // Defer all requests till subscribe is processed.
959  if (subscribe_pending) {
960  DBRequest *request_entry = new DBRequest();
961  request_entry->Swap(&req);
962  string table_name =
964  defer_q_.insert(make_pair(
965  make_pair(vrf_name, table_name), request_entry));
966  return true;
967  }
968 
969  assert(table);
970  BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
971  SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_TRACE,
972  "Multicast group " << item.entry.nlri.group <<
973  " source " << item.entry.nlri.source <<
974  " and label range " << label_range <<
975  " enqueued for " << (add_change ? "add/change" : "delete"));
976  table->Enqueue(&req);
977  return true;
978 }
979 
981  IpAddress src_address, bool add_change, uint64_t subscription_gen_id,
982  int instance_id, DBRequest& req, const MvpnNextHopType &nexthop) {
985  grp_address.to_v4(), src_address.to_v4());
986  uint32_t flags = 0;
987 
988  // Build and enqueue a DB request for route-addition
989  req.key.reset(new MvpnTable::RequestKey(mc_prefix, peer_.get()));
990 
991  if (add_change) {
993 
994  BgpAttrSpec attrs;
995  // Next-hop ip address
996  IpAddress nh_address;
997  if (!XmppDecodeAddress(nexthop.af, nexthop.address, &nh_address)) {
998  return;
999  }
1000 
1001  BgpAttrSourceRd source_rd(
1002  RouteDistinguisher(nh_address.to_v4().to_ulong(), instance_id));
1003  attrs.push_back(&source_rd);
1004  BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attrs);
1005  req.data.reset(new MvpnTable::RequestData(
1006  attr, flags, 0, 0, subscription_gen_id));
1007  stats_[RX].reach++;
1008  } else {
1010  stats_[RX].unreach++;
1011  }
1012 }
1013 
1015  IpAddress src_address, bool add_change, uint64_t subscription_gen_id,
1016  DBRequest& req) {
1018  MvpnPrefix mc_prefix(MvpnPrefix::SourceTreeJoinRoute, mc_rd, 0,
1019  grp_address.to_v4(), src_address.to_v4());
1020  uint32_t flags = BgpPath::ResolveNexthop;
1021 
1022  // Build and enqueue a DB request for route-addition
1023  req.key.reset(new MvpnTable::RequestKey(mc_prefix, peer_.get()));
1024 
1025  if (add_change) {
1027 
1028  BgpAttrSpec attrs;
1029 
1030  // Next-hop ip address
1031  BgpAttrNextHop nexthop(src_address);
1032  attrs.push_back(&nexthop);
1033 
1034  BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attrs);
1035  req.data.reset(new MvpnTable::RequestData(
1036  attr, flags, 0, 0, subscription_gen_id));
1037  stats_[RX].reach++;
1038  } else {
1040  stats_[RX].unreach++;
1041  }
1042 }
1043 
1044 bool BgpXmppChannel::ProcessMvpnItem(string vrf_name,
1045  const pugi::xml_node &node, bool add_change) {
1046  MvpnItemType item;
1047  item.Clear();
1048 
1049  if (!item.XmlParse(node)) {
1050  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1051  BGP_LOG_FLAG_ALL, "Invalid multicast route message received");
1052  return false;
1053  }
1054 
1055  if (item.entry.nlri.af != BgpAf::IPv4) {
1057  "Unsupported address family " << item.entry.nlri.af <<
1058  " for multicast route");
1059  return false;
1060  }
1061 
1062  if (item.entry.nlri.safi != BgpAf::MVpn) {
1063  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1064  BGP_LOG_FLAG_ALL, "Unsupported subsequent address family " <<
1065  item.entry.nlri.safi << " for multicast route");
1066  return false;
1067  }
1068 
1069  if (item.entry.nlri.group.empty()) {
1071  "Mandatory group address not specified");
1072  return false;
1073  }
1074 
1075  error_code error;
1076  IpAddress grp_address = IpAddress::from_string("0.0.0.0", error);
1077  if (!XmppDecodeAddress(item.entry.nlri.af,
1078  item.entry.nlri.group, &grp_address, false)) {
1080  "Bad group address " << item.entry.nlri.group);
1081  return false;
1082  }
1083 
1084  if (item.entry.nlri.source.empty()) {
1086  "Mandatory source address not specified");
1087  return false;
1088  }
1089 
1090  IpAddress src_address = IpAddress::from_string("0.0.0.0", error);
1091  if (!XmppDecodeAddress(item.entry.nlri.af,
1092  item.entry.nlri.source, &src_address, true)) {
1094  "Bad source address " << item.entry.nlri.source);
1095  return false;
1096  }
1097 
1098  bool subscribe_pending;
1099  int instance_id;
1100  uint64_t subscription_gen_id;
1101  BgpTable *table;
1102  if (!VerifyMembership(vrf_name, Address::MVPN, &table, &instance_id,
1103  &subscription_gen_id, &subscribe_pending, add_change)) {
1104  channel_->Close();
1105  return false;
1106  }
1107 
1108  int rt_type = item.entry.nlri.route_type;
1109  DBRequest req;
1110  // Build the key to the Multicast DBTable
1111  if (rt_type == MvpnPrefix::SourceTreeJoinRoute) {
1112  CreateType7MvpnRouteRequest(grp_address, src_address, add_change,
1113  subscription_gen_id, req);
1114  } else if (rt_type == MvpnPrefix::SourceActiveADRoute) {
1115  CreateType5MvpnRouteRequest(grp_address, src_address, add_change,
1116  subscription_gen_id, instance_id, req, item.entry.next_hop);
1117  } else {
1119  "Unsupported route type " << item.entry.nlri.route_type);
1120  return false;
1121  }
1122 
1123  // Need to locate path resolver if not done already
1124  assert(table);
1125  table->LocatePathResolver();
1126 
1127  // Defer all requests till subscribe is processed.
1128  if (subscribe_pending) {
1129  DBRequest *request_entry = new DBRequest();
1130  request_entry->Swap(&req);
1131  string table_name =
1133  defer_q_.insert(make_pair(
1134  make_pair(vrf_name, table_name), request_entry));
1135  return true;
1136  }
1137 
1138  BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
1139  SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_TRACE,
1140  "Multicast group " << item.entry.nlri.group <<
1141  " source " << item.entry.nlri.source <<
1142  " enqueued for " << (add_change ? "add/change" : "delete"));
1143  table->Enqueue(&req);
1144  return true;
1145 }
1146 
1147 bool BgpXmppChannel::ProcessItem(string vrf_name,
1148  const pugi::xml_node &node, bool add_change, int primary_instance_id) {
1149  ItemType item;
1150  item.Clear();
1151 
1152  if (!item.XmlParse(node)) {
1154  "Invalid inet route message received");
1155  return false;
1156  }
1157 
1158  if (item.entry.nlri.af != BgpAf::IPv4) {
1160  "Unsupported address family " << item.entry.nlri.af <<
1161  " for inet route " << item.entry.nlri.address);
1162  return false;
1163  }
1164 
1165  if ((item.entry.nlri.safi != BgpAf::Unicast) &&
1166  (item.entry.nlri.safi != BgpAf::Mpls)) {
1168  "Unsupported subsequent address family " << item.entry.nlri.safi <<
1169  " for inet route " << item.entry.nlri.address);
1170  return false;
1171  }
1172  error_code error;
1173  Ip4Prefix inet_prefix =
1174  Ip4Prefix::FromString(item.entry.nlri.address, &error);
1175  if (error) {
1177  "Bad inet route " << item.entry.nlri.address);
1178  return false;
1179  }
1180 
1181  if (add_change && item.entry.next_hops.next_hop.empty()) {
1183  "Missing next-hops for inet route " << inet_prefix.ToString());
1184  return false;
1185  }
1186 
1187  // Rules for routes in master instance:
1188  // - Label must be 0 unless it is INETMPLS
1189  // - Tunnel encapsulation is not required
1190  // - Do not add SourceRd and ExtCommunitySpec
1191  bool master = (vrf_name == BgpConfigManager::kMasterInstance);
1192  bool subscribe_pending;
1193  int instance_id;
1194  uint64_t subscription_gen_id;
1195  BgpTable *table;
1196  Address::Family family = BgpAf::AfiSafiToFamily(item.entry.nlri.af,
1197  item.entry.nlri.safi);
1198  if (!VerifyMembership(vrf_name, family, &table, &instance_id,
1199  &subscription_gen_id, &subscribe_pending, add_change)) {
1200  channel_->Close();
1201  return false;
1202  }
1203 
1204  DBRequest req;
1205  req.key.reset(new InetTable::RequestKey(inet_prefix, peer_.get()));
1206 
1207  IpAddress nh_address(Ip4Address(0));
1208  uint32_t label = 0;
1209  uint32_t flags = 0;
1210  ExtCommunitySpec ext;
1211  LargeCommunitySpec largecomm;
1212  CommunitySpec comm;
1213 
1214  if (add_change) {
1216  BgpAttrSpec attrs;
1217 
1218  const NextHopListType &inh_list = item.entry.next_hops;
1219 
1220  // Agents should send only one next-hop in the item.
1221  if (inh_list.next_hop.size() != 1) {
1222  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1224  "More than one nexthop received for inet route " <<
1225  inet_prefix.ToString());
1226  return false;
1227  }
1228 
1229  NextHopListType::const_iterator nit = inh_list.begin();
1230 
1231  IpAddress nhop_address(Ip4Address(0));
1232  if (!XmppDecodeAddress(nit->af, nit->address, &nhop_address)) {
1233  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1235  "Bad nexthop address " << nit->address <<
1236  " for inet route " << inet_prefix.ToString());
1237  return false;
1238  }
1239 
1240  if (nit->label > EvpnPrefix::kMaxVniSigned ||
1241  ((master && nit->label) &&
1242  !(family == Address::INETMPLS))) {
1243  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1245  "Bad label " << nit->label <<
1246  " for inet route " << inet_prefix.ToString());
1247  return false;
1248  }
1249  if ((!master || (master && (family == Address::INETMPLS))) &&
1250  !nit->label) {
1251  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1253  "Bad label " << nit->label <<
1254  " for inet route in master instance(mpls)/non master instance" <<
1255  inet_prefix.ToString());
1256  return false;
1257  }
1258 
1259  nh_address = nhop_address;
1260  label = nit->label;
1261 
1262  // Process tunnel encapsulation list.
1263  bool no_tunnel_encap = true;
1264  bool no_valid_tunnel_encap = true;
1265  for (TunnelEncapsulationListType::const_iterator eit =
1266  nit->tunnel_encapsulation_list.begin();
1267  eit != nit->tunnel_encapsulation_list.end(); ++eit) {
1268  no_tunnel_encap = false;
1269  TunnelEncap tun_encap(*eit);
1270  if (tun_encap.tunnel_encap() == TunnelEncapType::UNSPEC)
1271  continue;
1272  no_valid_tunnel_encap = false;
1273  ext.communities.push_back(tun_encap.GetExtCommunityValue());
1274  }
1275 
1276  // Mark the path as infeasible if all tunnel encaps published
1277  // by agent are invalid.
1278  if (!no_tunnel_encap && no_valid_tunnel_encap && !master) {
1279  flags = BgpPath::NoTunnelEncap;
1280  }
1281 
1282  // Process router-mac as ext-community.
1283  if (!nit->mac.empty()) {
1284  MacAddress mac_addr =
1285  MacAddress::FromString(nit->mac, &error);
1286  if (error) {
1287  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1289  "Bad next-hop mac address " << nit->mac);
1290  return false;
1291  }
1292  if (!mac_addr.IsZero()) {
1293  RouterMac router_mac(mac_addr);
1294  ext.communities.push_back(router_mac.GetExtCommunityValue());
1295  }
1296  }
1297 
1298  // Process tags list.
1299  uint64_t tag_val = 0;
1300  for (TagListType::const_iterator tit = nit->tag_list.begin();
1301  tit != nit->tag_list.end(); ++tit) {
1302  tag_val = nit->is_new_tags_list ? *tit :
1303  ((0xFFFF0000 & *tit) << 16) | (0x0000FFFF & *tit);
1304  TagLC tag_lc(bgp_server_->autonomous_system(), tag_val);
1305  for (const auto &value_data : tag_lc.GetLargeCommunityValue()) {
1306  largecomm.communities.push_back(value_data);
1307  }
1308  }
1309 
1310  // Process local sequence_number
1311  if (nit->local_sequence_number) {
1312  LocalSequenceNumber lsn (nit->local_sequence_number);
1313  ext.communities.push_back(lsn.GetExtCommunityValue());
1314  }
1315 
1316  BgpAttrLocalPref local_pref(item.entry.local_preference);
1317  if (local_pref.local_pref != 0)
1318  attrs.push_back(&local_pref);
1319 
1320  // If there's no explicit med, calculate it automatically from the
1321  // local pref.
1322  uint32_t med_value = item.entry.med;
1323  if (!med_value)
1324  med_value = GetMedFromLocalPref(local_pref.local_pref);
1325  BgpAttrMultiExitDisc med(med_value);
1326  if (med.med != 0)
1327  attrs.push_back(&med);
1328 
1329  // Process community tags.
1330  const CommunityTagListType &ict_list = item.entry.community_tag_list;
1331  for (CommunityTagListType::const_iterator cit = ict_list.begin();
1332  cit != ict_list.end(); ++cit) {
1333  error_code error;
1334  uint32_t rt_community =
1335  CommunityType::CommunityFromString(*cit, &error);
1336  if (error)
1337  continue;
1338  comm.communities.push_back(rt_community);
1339  }
1340 
1341  uint32_t addr = nh_address.to_v4().to_ulong();
1342  BgpAttrNextHop nexthop(addr);
1343  attrs.push_back(&nexthop);
1344  uint16_t cluster_seed =
1346  BgpAttrSourceRd source_rd;
1347  if (!master || primary_instance_id) {
1348  if (master)
1349  instance_id = primary_instance_id;
1350  if (cluster_seed) {
1351  source_rd = BgpAttrSourceRd(
1352  RouteDistinguisher(cluster_seed, addr, instance_id));
1353  } else {
1354  source_rd = BgpAttrSourceRd(
1355  RouteDistinguisher(addr, instance_id));
1356  }
1357  attrs.push_back(&source_rd);
1358  }
1359 
1360  // Process security group list.
1361  uint16_t sg_index = 0;
1362  const SecurityGroupListType &isg_list = item.entry.security_group_list;
1363  for (SecurityGroupListType::const_iterator sit = isg_list.begin();
1364  sit != isg_list.end(); ++sit) {
1367  ext.communities.push_back(sg.GetExtCommunityValue());
1368  } else {
1369  SecurityGroup sg(sg_index, *sit);
1371  sg_index++);
1372  ext.communities.push_back(sg4.GetExtCommunityValue());
1373  ext.communities.push_back(sg.GetExtCommunityValue());
1374  }
1375  }
1376 
1377  if (item.entry.mobility.seqno) {
1378  MacMobility mm(item.entry.mobility.seqno,
1379  item.entry.mobility.sticky);
1380  ext.communities.push_back(mm.GetExtCommunityValue());
1381  } else if (item.entry.sequence_number) {
1382  MacMobility mm(item.entry.sequence_number);
1383  ext.communities.push_back(mm.GetExtCommunityValue());
1384  }
1385 
1386  // Process load-balance extended community.
1387  LoadBalance load_balance(item.entry.load_balance);
1388  if (!load_balance.IsDefault())
1389  ext.communities.push_back(load_balance.GetExtCommunityValue());
1390 
1391  if (!comm.communities.empty())
1392  attrs.push_back(&comm);
1393  if (!master && !ext.communities.empty())
1394  attrs.push_back(&ext);
1395  if (!master && !largecomm.communities.empty())
1396  attrs.push_back(&largecomm);
1397 
1398  // Process sub-protocol(route types)
1399  BgpAttrSubProtocol sbp(item.entry.sub_protocol);
1400  attrs.push_back(&sbp);
1401 
1402  BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attrs);
1403  req.data.reset(new BgpTable::RequestData(
1404  attr, flags, label, 0, subscription_gen_id));
1405  } else {
1407  }
1408 
1409  // Defer all requests till subscribe is processed.
1410  if (subscribe_pending) {
1411  DBRequest *request_entry = new DBRequest();
1412  request_entry->Swap(&req);
1413  string table_name =
1414  RoutingInstance::GetTableName(vrf_name, family);
1415  defer_q_.insert(make_pair(
1416  make_pair(vrf_name, table_name), request_entry));
1417  return true;
1418  }
1419 
1420  assert(table);
1421  BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
1422  SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_TRACE,
1423  "Inet route " << item.entry.nlri.address <<
1424  " with next-hop " << nh_address << " and label " << label <<
1425  " enqueued for " << (add_change ? "add/change" : "delete") <<
1426  " to table " << table->name());
1427  table->Enqueue(&req);
1428 
1429  if (add_change) {
1430  stats_[RX].reach++;
1431  } else {
1432  stats_[RX].unreach++;
1433  }
1434 
1435  return true;
1436 }
1437 
1439  const pugi::xml_node &node, bool add_change) {
1440  ItemType item;
1441  item.Clear();
1442 
1443  if (!item.XmlParse(node)) {
1446  "Invalid inet6 route message received");
1447  return false;
1448  }
1449 
1450  if (item.entry.nlri.af != BgpAf::IPv6) {
1453  "Unsupported address family " << item.entry.nlri.af <<
1454  " for inet6 route " << item.entry.nlri.address);
1455  return false;
1456  }
1457 
1458  if (item.entry.nlri.safi != BgpAf::Unicast) {
1461  "Unsupported subsequent address family " << item.entry.nlri.safi <<
1462  " for inet6 route " << item.entry.nlri.address);
1463  return false;
1464  }
1465 
1466  error_code error;
1467  Inet6Prefix inet6_prefix =
1468  Inet6Prefix::FromString(item.entry.nlri.address, &error);
1469  if (error) {
1472  "Bad inet6 route " << item.entry.nlri.address);
1473  return false;
1474  }
1475 
1476  if (add_change && item.entry.next_hops.next_hop.empty()) {
1478  "Missing next-hops for inet6 route " << inet6_prefix.ToString());
1479  return false;
1480  }
1481 
1482  // Rules for routes in master instance:
1483  // - Label must be 0
1484  // - Tunnel encapsulation is not required
1485  // - Do not add SourceRd and ExtCommunitySpec
1486  bool master = (vrf_name == BgpConfigManager::kMasterInstance);
1487 
1488  // vector<Address::Family> family_list = list_of(Address::INET6)(Address::EVPN);
1489  vector<Address::Family> family_list = list_of(Address::INET6);
1490  BOOST_FOREACH(Address::Family family, family_list) {
1491  bool subscribe_pending;
1492  int instance_id;
1493  uint64_t subscription_gen_id;
1494  BgpTable *table;
1495  if (!VerifyMembership(vrf_name, family, &table, &instance_id,
1496  &subscription_gen_id, &subscribe_pending, add_change)) {
1497  channel_->Close();
1498  return false;
1499  }
1500 
1501  DBRequest req;
1502  if (family == Address::INET6) {
1503  req.key.reset(new Inet6Table::RequestKey(inet6_prefix, peer_.get()));
1504  } else {
1506  inet6_prefix.addr(), inet6_prefix.prefixlen());
1507  req.key.reset(new EvpnTable::RequestKey(evpn_prefix, peer_.get()));
1508  }
1509 
1510  IpAddress nh_address(Ip4Address(0));
1511  uint32_t label = 0;
1512  uint32_t flags = 0;
1513  ExtCommunitySpec ext;
1514  LargeCommunitySpec largecomm;
1515  CommunitySpec comm;
1516 
1517  if (add_change) {
1519  BgpAttrSpec attrs;
1520 
1521  const NextHopListType &inh_list = item.entry.next_hops;
1522 
1523  // Agents should send only one next-hop in the item.
1524  if (inh_list.next_hop.size() != 1) {
1525  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1527  "More than one nexthop received for inet6 route " <<
1528  inet6_prefix.ToString());
1529  return false;
1530  }
1531 
1532  NextHopListType::const_iterator nit = inh_list.begin();
1533 
1534  IpAddress nhop_address(Ip4Address(0));
1535  if (!XmppDecodeAddress(nit->af, nit->address, &nhop_address)) {
1537  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1539  "Bad nexthop address " << nit->address <<
1540  " for inet6 route " << inet6_prefix.ToString());
1541  return false;
1542  }
1543 
1544  if (family == Address::EVPN) {
1545  if (nit->vni > EvpnPrefix::kMaxVniSigned) {
1546  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1548  "Bad label " << nit->vni <<
1549  " for inet6 route " << inet6_prefix.ToString());
1550  return false;
1551  }
1552  if (!nit->vni)
1553  continue;
1554  if (nit->mac.empty())
1555  continue;
1556 
1557  MacAddress mac_addr =
1558  MacAddress::FromString(nit->mac, &error);
1559  if (error) {
1560  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1562  "Bad next-hop mac address " << nit->mac);
1563  return false;
1564  }
1565  RouterMac router_mac(mac_addr);
1566  ext.communities.push_back(router_mac.GetExtCommunityValue());
1567  } else {
1568  if (nit->label > EvpnPrefix::kMaxVniSigned || (master && nit->label)) {
1569  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1571  "Bad label " << nit->label <<
1572  " for inet6 route " << inet6_prefix.ToString());
1573  return false;
1574  }
1575  if (!master && !nit->label)
1576  continue;
1577  }
1578 
1579  nh_address = nhop_address;
1580  if (family == Address::INET6) {
1581  label = nit->label;
1582  } else {
1583  label = nit->vni;
1584  }
1585 
1586  // Process tunnel encapsulation list.
1587  bool no_tunnel_encap = true;
1588  bool no_valid_tunnel_encap = true;
1589  for (TunnelEncapsulationListType::const_iterator eit =
1590  nit->tunnel_encapsulation_list.begin();
1591  eit != nit->tunnel_encapsulation_list.end(); ++eit) {
1592  no_tunnel_encap = false;
1593  TunnelEncap tun_encap(*eit);
1594  if (tun_encap.tunnel_encap() == TunnelEncapType::UNSPEC)
1595  continue;
1596  no_valid_tunnel_encap = false;
1597  ext.communities.push_back(tun_encap.GetExtCommunityValue());
1598  }
1599 
1600  // Mark the path as infeasible if all tunnel encaps published
1601  // by agent are invalid.
1602  if (!no_tunnel_encap && no_valid_tunnel_encap && !master) {
1603  flags = BgpPath::NoTunnelEncap;
1604  }
1605 
1606  // Process router-mac as ext-community.
1607  if (!nit->mac.empty()) {
1608  MacAddress mac_addr =
1609  MacAddress::FromString(nit->mac, &error);
1610  if (error) {
1611  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1613  "Bad next-hop mac address " << nit->mac);
1614  return false;
1615  }
1616  if (!mac_addr.IsZero()) {
1617  RouterMac router_mac(mac_addr);
1618  ext.communities.push_back(router_mac.GetExtCommunityValue());
1619  }
1620  }
1621 
1622  // Process tags list.
1623  uint64_t tag_val = 0;
1624  for (TagListType::const_iterator tit = nit->tag_list.begin();
1625  tit != nit->tag_list.end(); ++tit) {
1626  tag_val = nit->is_new_tags_list ? *tit :
1627  ((0xFFFF0000 & *tit) << 16) | (0x0000FFFF & *tit);
1628  TagLC tag_lc(bgp_server_->autonomous_system(), tag_val);
1629  for (const auto &value_data :
1630  tag_lc.GetLargeCommunityValue()) {
1631  largecomm.communities.push_back(value_data);
1632  }
1633  }
1634 
1635  // Process local sequence_number
1636  if (nit->local_sequence_number) {
1637  LocalSequenceNumber lsn (nit->local_sequence_number);
1638  ext.communities.push_back(lsn.GetExtCommunityValue());
1639  }
1640 
1641  BgpAttrLocalPref local_pref(item.entry.local_preference);
1642  if (local_pref.local_pref != 0)
1643  attrs.push_back(&local_pref);
1644 
1645  // If there's no explicit med, calculate it automatically from the
1646  // local pref.
1647  uint32_t med_value = item.entry.med;
1648  if (!med_value)
1649  med_value = GetMedFromLocalPref(local_pref.local_pref);
1650  BgpAttrMultiExitDisc med(med_value);
1651  if (med.med != 0)
1652  attrs.push_back(&med);
1653 
1654  // Process community tags.
1655  const CommunityTagListType &ict_list =
1656  item.entry.community_tag_list;
1657  for (CommunityTagListType::const_iterator cit = ict_list.begin();
1658  cit != ict_list.end(); ++cit) {
1659  error_code error;
1660  uint32_t rt_community =
1661  CommunityType::CommunityFromString(*cit, &error);
1662  if (error)
1663  continue;
1664  comm.communities.push_back(rt_community);
1665  }
1666 
1667  BgpAttrNextHop nexthop(nh_address);
1668  attrs.push_back(&nexthop);
1669 
1670  BgpAttrSourceRd source_rd;
1671  if (!master) {
1672  uint32_t addr = nh_address.to_v4().to_ulong();
1673  uint16_t cluster_seed =
1675  if (cluster_seed) {
1676  source_rd = BgpAttrSourceRd(
1677  RouteDistinguisher(cluster_seed, addr, instance_id));
1678  } else {
1679  source_rd = BgpAttrSourceRd(
1680  RouteDistinguisher(addr, instance_id));
1681  }
1682  attrs.push_back(&source_rd);
1683  }
1684 
1685  // Process security group list.
1686  const SecurityGroupListType &isg_list =
1687  item.entry.security_group_list;
1688  uint16_t sg_index = 0;
1689  for (SecurityGroupListType::const_iterator sit = isg_list.begin();
1690  sit != isg_list.end(); ++sit) {
1693  ext.communities.push_back(sg.GetExtCommunityValue());
1694  } else {
1695  SecurityGroup sg(sg_index, *sit);
1697  sg_index++);
1698  ext.communities.push_back(sg4.GetExtCommunityValue());
1699  ext.communities.push_back(sg.GetExtCommunityValue());
1700  }
1701  }
1702 
1703  if (item.entry.mobility.seqno) {
1704  MacMobility mm(item.entry.mobility.seqno,
1705  item.entry.mobility.sticky);
1706  ext.communities.push_back(mm.GetExtCommunityValue());
1707  } else if (item.entry.sequence_number) {
1708  MacMobility mm(item.entry.sequence_number);
1709  ext.communities.push_back(mm.GetExtCommunityValue());
1710  }
1711 
1712  // Process load-balance extended community.
1713  LoadBalance load_balance(item.entry.load_balance);
1714  if (!load_balance.IsDefault())
1715  ext.communities.push_back(load_balance.GetExtCommunityValue());
1716 
1717  // Process sub-protocol(route types)
1718  BgpAttrSubProtocol sbp(item.entry.sub_protocol);
1719  attrs.push_back(&sbp);
1720 
1721  if (!comm.communities.empty())
1722  attrs.push_back(&comm);
1723  if (!master && !ext.communities.empty())
1724  attrs.push_back(&ext);
1725  if (!master && !largecomm.communities.empty())
1726  attrs.push_back(&largecomm);
1727 
1728  BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attrs);
1729  req.data.reset(new BgpTable::RequestData(
1730  attr, flags, label, 0, subscription_gen_id));
1731  } else {
1733  }
1734 
1735  // Defer all requests till subscribe is processed.
1736  if (subscribe_pending) {
1737  DBRequest *request_entry = new DBRequest();
1738  request_entry->Swap(&req);
1739  string table_name =
1740  RoutingInstance::GetTableName(vrf_name, family);
1741  defer_q_.insert(make_pair(
1742  make_pair(vrf_name, table_name), request_entry));
1743  continue;
1744  }
1745 
1746  assert(table);
1747  BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
1748  SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_TRACE,
1749  "Inet6 route " << item.entry.nlri.address <<
1750  " with next-hop " << nh_address << " and label " << label <<
1751  " enqueued for " << (add_change ? "add/change" : "delete") <<
1752  " to table " << table->name());
1753  table->Enqueue(&req);
1754  }
1755 
1756  if (add_change) {
1757  stats_[RX].reach++;
1758  } else {
1759  stats_[RX].unreach++;
1760  }
1761 
1762  return true;
1763 }
1764 
1765 bool BgpXmppChannel::ProcessEnetItem(string vrf_name,
1766  const pugi::xml_node &node, bool add_change) {
1767  EnetItemType item;
1768  item.Clear();
1769 
1770  if (!item.XmlParse(node)) {
1772  "Invalid enet route message received");
1773  return false;
1774  }
1775 
1776  if (item.entry.nlri.af != BgpAf::L2Vpn) {
1778  "Unsupported address family " << item.entry.nlri.af <<
1779  " for enet route " << item.entry.nlri.address);
1780  return false;
1781  }
1782 
1783  if (item.entry.nlri.safi != BgpAf::Enet) {
1785  "Unsupported subsequent address family " << item.entry.nlri.safi <<
1786  " for enet route " << item.entry.nlri.mac);
1787  return false;
1788  }
1789 
1790  bool type6 = false;
1791  error_code error;
1792  IpAddress group= IpAddress::from_string("0.0.0.0", error);
1793  if (!item.entry.nlri.group.empty()) {
1794  type6 = true;
1795  if (!XmppDecodeAddress(item.entry.nlri.af,
1796  item.entry.nlri.group, &group, false)) {
1798  "Bad group address " << item.entry.nlri.group);
1799  }
1800  }
1801 
1802  IpAddress source = IpAddress::from_string("0.0.0.0", error);
1803  if (!item.entry.nlri.source.empty() && !XmppDecodeAddress(
1804  item.entry.nlri.af, item.entry.nlri.source, &source, true)) {
1806  "Bad source address " << item.entry.nlri.source);
1807  }
1808 
1809  //error_code error;
1810  MacAddress mac_addr = MacAddress::FromString(item.entry.nlri.mac, &error);
1811 
1812  if (error) {
1814  "Bad mac address " << item.entry.nlri.mac);
1815  return false;
1816  }
1817 
1818  bool type2 = type6 ? false : !mac_addr.IsZero();
1819  Ip4Prefix inet_prefix;
1820  Inet6Prefix inet6_prefix;
1821  IpAddress ip_addr;
1822  int prefix_len = 0;
1823  if (!item.entry.nlri.address.empty()) {
1824  size_t pos = item.entry.nlri.address.find('/');
1825  if (pos == string::npos) {
1827  "Missing / in address " << item.entry.nlri.address);
1828  return false;
1829  }
1830 
1831  bool ipv6 = item.entry.nlri.address.find(':') != string::npos;
1832  if (!ipv6) {
1833  inet_prefix =
1834  Ip4Prefix::FromString(item.entry.nlri.address, &error);
1835  if (error) {
1836  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1838  "Cannot parse inet prefix string " <<
1839  item.entry.nlri.address);
1840  return false;
1841  }
1842 
1843  if (type2 && inet_prefix.prefixlen() != 32 &&
1844  item.entry.nlri.address != "0.0.0.0/0") {
1845  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1847  "Bad inet address " << item.entry.nlri.address);
1848  return false;
1849  }
1850 
1851  ip_addr = inet_prefix.ip4_addr();
1852  prefix_len = inet_prefix.prefixlen();
1853  } else {
1854  inet6_prefix =
1855  Inet6Prefix::FromString(item.entry.nlri.address, &error);
1856 
1857  if (error) {
1858  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1860  "Cannot parse inet6 prefix string " <<
1861  item.entry.nlri.address);
1862  return false;
1863  }
1864 
1865  if (type2 && inet6_prefix.prefixlen() != 128 &&
1866  item.entry.nlri.address != "::/0") {
1867  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1869  "Bad inet6 address " << item.entry.nlri.address);
1870  return false;
1871  }
1872  ip_addr = inet6_prefix.ip6_addr();
1873  prefix_len = inet6_prefix.prefixlen();
1874  }
1875  }
1876 
1877  bool subscribe_pending;
1878  int instance_id;
1879  uint64_t subscription_gen_id;
1880  BgpTable *table;
1881  if (!VerifyMembership(vrf_name, Address::EVPN, &table, &instance_id,
1882  &subscription_gen_id, &subscribe_pending, add_change)) {
1883  channel_->Close();
1884  return false;
1885  }
1886 
1887  RouteDistinguisher rd;
1888  if (mac_addr.IsBroadcast()) {
1889  rd = RouteDistinguisher(peer_->bgp_identifier(), instance_id);
1890  } else if (type6) {
1892  table->routing_instance()->index());
1893  } else {
1895  }
1896 
1897  uint32_t ethernet_tag = item.entry.nlri.ethernet_tag;
1898  EvpnPrefix evpn_prefix = type6 ?
1899  EvpnPrefix(rd, ethernet_tag, source, group,
1901  type2 ? EvpnPrefix(rd, ethernet_tag, mac_addr, ip_addr) :
1902  EvpnPrefix(rd, ip_addr, prefix_len);
1903 
1904  DBRequest req;
1905  ExtCommunitySpec ext;
1906  LargeCommunitySpec largecomm;
1907  req.key.reset(new EvpnTable::RequestKey(evpn_prefix, peer_.get()));
1908 
1909  IpAddress nh_address(Ip4Address(0));
1910  uint32_t label = 0;
1911  uint32_t l3_label = 0;
1912  uint32_t flags = 0;
1913 
1914  if (add_change) {
1916  BgpAttrSpec attrs;
1917  const EnetNextHopListType &inh_list = item.entry.next_hops;
1918 
1919  if (inh_list.next_hop.empty()) {
1920  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1921  BGP_LOG_FLAG_ALL, "Missing next-hops for enet route " <<
1922  evpn_prefix.ToXmppIdString());
1923  return false;
1924  }
1925 
1926  // Agents should send only one next-hop in the item.
1927  if (inh_list.next_hop.size() != 1) {
1928  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1930  "More than one nexthop received for enet route " <<
1931  evpn_prefix.ToXmppIdString());
1932  return false;
1933  }
1934 
1935  EnetNextHopListType::const_iterator nit = inh_list.begin();
1936 
1937  IpAddress nhop_address(Ip4Address(0));
1938 
1939  if (!XmppDecodeAddress(nit->af, nit->address, &nhop_address)) {
1940  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1941  BGP_LOG_FLAG_ALL, "Bad nexthop address " << nit->address <<
1942  " for enet route " << evpn_prefix.ToXmppIdString());
1943  return false;
1944  }
1945 
1946  nh_address = nhop_address;
1947  label = nit->label;
1948  l3_label = nit->l3_label;
1949  if (!nit->mac.empty()) {
1950  MacAddress rmac_addr =
1951  MacAddress::FromString(nit->mac, &error);
1952  if (error) {
1953  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
1955  "Bad next-hop mac address " << nit->mac <<
1956  " for enet route " << evpn_prefix.ToXmppIdString());
1957  return false;
1958  }
1959  RouterMac router_mac(rmac_addr);
1960  ext.communities.push_back(router_mac.GetExtCommunityValue());
1961  }
1962 
1963  // Process tunnel encapsulation list.
1964  bool no_tunnel_encap = true;
1965  bool no_valid_tunnel_encap = true;
1966  for (EnetTunnelEncapsulationListType::const_iterator eit =
1967  nit->tunnel_encapsulation_list.begin();
1968  eit != nit->tunnel_encapsulation_list.end(); ++eit) {
1969  no_tunnel_encap = false;
1970  TunnelEncap tun_encap(*eit);
1971  if (tun_encap.tunnel_encap() == TunnelEncapType::UNSPEC)
1972  continue;
1973  no_valid_tunnel_encap = false;
1974  ext.communities.push_back(tun_encap.GetExtCommunityValue());
1975  if (tun_encap.tunnel_encap() == TunnelEncapType::GRE) {
1977  ext.communities.push_back(alt_tun_encap.GetExtCommunityValue());
1978  }
1979  }
1980 
1981  // Mark the path as infeasible if all tunnel encaps published
1982  // by agent are invalid.
1983  if (!no_tunnel_encap && no_valid_tunnel_encap) {
1984  flags = BgpPath::NoTunnelEncap;
1985  }
1986 
1987  // Process tags list.
1988  uint64_t tag_val = 0;
1989  for (TagListType::const_iterator tit = nit->tag_list.begin();
1990  tit != nit->tag_list.end(); ++tit) {
1991  tag_val = nit->is_new_tags_list ? *tit :
1992  ((0x0000FFFF0000 & *tit) << 16) |
1993  (0x00000000FFFF & *tit);
1994  TagLC tag_lc(bgp_server_->autonomous_system(), tag_val);
1995  for (const auto &value_data : tag_lc.GetLargeCommunityValue()) {
1996  largecomm.communities.push_back(value_data);
1997  }
1998  }
1999 
2000  // Process local sequence_number
2001  if (nit->local_sequence_number) {
2002  LocalSequenceNumber lsn (nit->local_sequence_number);
2003  ext.communities.push_back(lsn.GetExtCommunityValue());
2004  }
2005 
2006  BgpAttrLocalPref local_pref(item.entry.local_preference);
2007  if (local_pref.local_pref != 0) {
2008  attrs.push_back(&local_pref);
2009  }
2010 
2011  // If there's no explicit med, calculate it automatically from the
2012  // local pref.
2013  uint32_t med_value = item.entry.med;
2014  if (!med_value)
2015  med_value = GetMedFromLocalPref(local_pref.local_pref);
2016  BgpAttrMultiExitDisc med(med_value);
2017  if (med.med != 0)
2018  attrs.push_back(&med);
2019 
2020  BgpAttrNextHop nexthop(nh_address.to_v4().to_ulong());
2021  if (type6) {
2023  if (item.entry.replicator_address.empty() &&
2024  item.entry.edge_replication_not_supported) {
2025  // Only for test to inject remote smet routes
2026  flags &= ~BgpPath::CheckGlobalErmVpnRoute;
2027  attrs.push_back(&nexthop);
2028  }
2029  } else {
2030  attrs.push_back(&nexthop);
2031  }
2032 
2033  uint16_t cluster_seed = bgp_server_->global_config()->rd_cluster_seed();
2034  BgpAttrSourceRd source_rd;
2035  if (cluster_seed) {
2036  source_rd = BgpAttrSourceRd(RouteDistinguisher(cluster_seed,
2037  nh_address.to_v4().to_ulong(), instance_id));
2038  } else {
2039  source_rd = BgpAttrSourceRd(RouteDistinguisher(
2040  nh_address.to_v4().to_ulong(), instance_id));
2041  }
2042  attrs.push_back(&source_rd);
2043 
2044  // Process security group list.
2045  const EnetSecurityGroupListType &isg_list =
2046  item.entry.security_group_list;
2047  uint16_t sg_index = 0;
2048  for (EnetSecurityGroupListType::const_iterator sit = isg_list.begin();
2049  sit != isg_list.end(); ++sit) {
2052  ext.communities.push_back(sg.GetExtCommunityValue());
2053  } else {
2054  SecurityGroup sg(sg_index, *sit);
2056  sg_index++);
2057  ext.communities.push_back(sg4.GetExtCommunityValue());
2058  ext.communities.push_back(sg.GetExtCommunityValue());
2059  }
2060  }
2061 
2062  if (item.entry.mobility.seqno) {
2063  MacMobility mm(item.entry.mobility.seqno,
2064  item.entry.mobility.sticky);
2065  ext.communities.push_back(mm.GetExtCommunityValue());
2066  } else if (item.entry.sequence_number) {
2067  MacMobility mm(item.entry.sequence_number);
2068  ext.communities.push_back(mm.GetExtCommunityValue());
2069  }
2070 
2071  ETree etree(item.entry.etree_leaf);
2072  ext.communities.push_back(etree.GetExtCommunityValue());
2073 
2074  if (!ext.communities.empty())
2075  attrs.push_back(&ext);
2076  if (!largecomm.communities.empty())
2077  attrs.push_back(&largecomm);
2078 
2079  PmsiTunnelSpec pmsi_spec;
2080  if (mac_addr.IsBroadcast()) {
2081  if (!item.entry.replicator_address.empty()) {
2082  IpAddress replicator_address;
2084  item.entry.replicator_address, &replicator_address)) {
2085  BGP_LOG_PEER_INSTANCE_WARNING(Peer(), vrf_name,
2087  "Bad replicator address " <<
2088  item.entry.replicator_address <<
2089  " for enet route " << evpn_prefix.ToXmppIdString());
2090  return false;
2091  }
2092  pmsi_spec.tunnel_type =
2095  pmsi_spec.SetIdentifier(replicator_address.to_v4());
2096  } else {
2098  if (item.entry.assisted_replication_supported) {
2101  }
2102  if (!item.entry.edge_replication_not_supported) {
2103  pmsi_spec.tunnel_flags |=
2105  }
2106  pmsi_spec.SetIdentifier(nh_address.to_v4());
2107  }
2108  ExtCommunity ext_comm(bgp_server_->extcomm_db(), ext);
2109  pmsi_spec.SetLabel(label, &ext_comm);
2110  attrs.push_back(&pmsi_spec);
2111  }
2112 
2113  BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attrs);
2114 
2115  req.data.reset(new EvpnTable::RequestData(
2116  attr, flags, label, l3_label, subscription_gen_id));
2117  stats_[RX].reach++;
2118  } else {
2120  stats_[RX].unreach++;
2121  }
2122 
2123  // Defer all requests till subscribe is processed.
2124  if (subscribe_pending) {
2125  DBRequest *request_entry = new DBRequest();
2126  request_entry->Swap(&req);
2127  string table_name =
2129  defer_q_.insert(make_pair(
2130  make_pair(vrf_name, table_name), request_entry));
2131  return true;
2132  }
2133 
2134  assert(table);
2135  BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
2136  SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_TRACE,
2137  "Enet route " << evpn_prefix.ToXmppIdString() <<
2138  " with next-hop " << nh_address <<
2139  " label " << label << " l3-label " << l3_label <<
2140  " enqueued for " << (add_change ? "add/change" : "delete"));
2141  table->Enqueue(&req);
2142  return true;
2143 }
2144 
2145 void BgpXmppChannel::DequeueRequest(const string &table_name,
2146  DBRequest *request) {
2147  unique_ptr<DBRequest> ptr(request);
2148 
2149  BgpTable *table = static_cast<BgpTable *>
2150  (bgp_server_->database()->FindTable(table_name));
2151  if (table == NULL || table->IsDeleted()) {
2152  return;
2153  }
2154 
2156  if (mgr) {
2157  int instance_id = -1;
2158  uint64_t subscription_gen_id = 0;
2159  bool is_registered = mgr->GetRegistrationInfo(peer_.get(), table,
2160  &instance_id, &subscription_gen_id);
2161  if (!is_registered) {
2162  BGP_LOG_PEER_WARNING(Membership, Peer(),
2164  "Not subscribed to table " << table->name());
2165  return;
2166  }
2167  if (ptr->oper == DBRequest::DB_ENTRY_ADD_CHANGE) {
2168  ((BgpTable::RequestData *)ptr->data.get())
2169  ->set_subscription_gen_id(subscription_gen_id);
2170  }
2171  }
2172 
2173  table->Enqueue(ptr.get());
2174 }
2175 
2177  peer_->Close(true);
2178  return true;
2179 }
2180 
2182  const TableMembershipRequestState *tmr_state) {
2183  // Defer if Membership manager is in use (by close manager).
2184  if (close_manager_->IsMembershipInUse()) {
2185  BGP_LOG_PEER_TABLE(Peer(), SandeshLevel::SYS_DEBUG,
2186  BGP_LOG_FLAG_ALL, table, "RegisterTable deferred "
2187  "from :" << line);
2188  return;
2189  }
2190 
2192  BGP_LOG_PEER(Membership, Peer(), SandeshLevel::SYS_DEBUG,
2194  "Subscribe to table " << table->name() <<
2195  (tmr_state->no_ribout ? " (no ribout)" : "") <<
2196  " with id " << tmr_state->instance_id);
2197  if (tmr_state->no_ribout) {
2198  mgr->RegisterRibIn(peer_.get(), table);
2199  mgr->SetRegistrationInfo(peer_.get(), table, tmr_state->instance_id,
2203  } else {
2204  mgr->Register(peer_.get(), table, bgp_policy_, tmr_state->instance_id);
2206  }
2207 
2208  // If EndOfRib Send timer is running, cancel it and reschedule it after all
2209  // outstanding membership registrations are complete.
2210  if (eor_send_timer_->running())
2212 }
2213 
2215  // Defer if Membership manager is in use (by close manager).
2216  if (close_manager_->IsMembershipInUse()) {
2217  BGP_LOG_PEER_TABLE(Peer(), SandeshLevel::SYS_DEBUG,
2218  BGP_LOG_FLAG_ALL, table, "UnregisterTable deferred "
2219  "from :" << line);
2220  return;
2221  }
2222 
2224  BGP_LOG_PEER(Membership, Peer(), SandeshLevel::SYS_DEBUG,
2226  "Unsubscribe to table " << table->name());
2227  mgr->Unregister(peer_.get(), table);
2229 }
2230 
2231 #define RegisterTable(table, tmr_state) \
2232  RegisterTable(__LINE__, table, tmr_state)
2233 #define UnregisterTable(table) UnregisterTable(__LINE__, table)
2234 
2235 // Process all pending membership requests of various tables.
2237  assert(!close_manager_->IsMembershipInUse());
2238  BOOST_FOREACH(TableMembershipRequestMap::value_type &entry,
2240  BgpTable *table = static_cast<BgpTable *>(
2241  bgp_server_->database()->FindTable(entry.first));
2242  const TableMembershipRequestState &tmr_state = entry.second;
2243  if (tmr_state.current_req == SUBSCRIBE) {
2244  RegisterTable(table, &tmr_state);
2245  } else {
2246  assert(tmr_state.current_req == UNSUBSCRIBE);
2247  UnregisterTable(table);
2248  }
2249  }
2250 }
2251 
2253  return table_membership_request_map_.size();
2254 }
2255 
2257  if (close_manager_->IsMembershipInUse()) {
2258  close_manager_->MembershipRequestCallback();
2259  return true;
2260  }
2261 
2262  TableMembershipRequestState *tmr_state =
2263  GetTableMembershipState(table_name);
2264  if (!tmr_state) {
2265  BGP_LOG_PEER_INSTANCE_CRITICAL(Peer(), table_name,
2267  "Table not in subscribe/unsubscribe request queue");
2268  assert(false);
2269  }
2270 
2271  if (tmr_state->current_req == SUBSCRIBE) {
2272  BGP_LOG_PEER(Membership, Peer(), SandeshLevel::SYS_DEBUG,
2274  "Subscribe to table " << table_name << " completed");
2276  } else {
2277  BGP_LOG_PEER(Membership, Peer(), SandeshLevel::SYS_DEBUG,
2279  "Unsubscribe to table " << table_name << " completed");
2281  }
2282 
2283  if (defer_peer_close_) {
2284  DeleteTableMembershipState(table_name);
2286  return true;
2287  defer_peer_close_ = false;
2288  ResumeClose();
2289  } else {
2290  ProcessMembershipResponse(table_name, tmr_state);
2291  }
2292 
2297 
2298  // Restart EndOfRib send if necessary.
2300 
2301  // If Close manager is waiting to use membership, try now.
2302  if (close_manager_->IsMembershipInWait())
2303  close_manager_->MembershipRequest();
2304 
2305  return true;
2306 }
2307 
2309  TableMembershipRequestState *tmr_state) {
2310  BgpTable *table = static_cast<BgpTable *>
2311  (bgp_server_->database()->FindTable(table_name));
2312  if (!table) {
2313  DeleteTableMembershipState(table_name);
2314  return true;
2315  }
2317 
2318  if ((tmr_state->current_req == UNSUBSCRIBE) &&
2319  (tmr_state->pending_req == SUBSCRIBE)) {
2320  // Process pending subscribe now that unsubscribe has completed.
2321  tmr_state->current_req = SUBSCRIBE;
2322  RegisterTable(table, tmr_state);
2323  return true;
2324  } else if ((tmr_state->current_req == SUBSCRIBE) &&
2325  (tmr_state->pending_req == UNSUBSCRIBE)) {
2326  // Process pending unsubscribe now that subscribe has completed.
2327  tmr_state->current_req = UNSUBSCRIBE;
2328  UnregisterTable(table);
2329  return true;
2330  } else if ((tmr_state->current_req == SUBSCRIBE) &&
2331  (tmr_state->pending_req == SUBSCRIBE) &&
2332  (mgr->IsRibOutRegistered(peer_.get(), table) == tmr_state->no_ribout)) {
2333  // Trigger an unsubscribe so that we can subsequently subscribe with
2334  // the updated value of no_ribout.
2335  tmr_state->current_req = UNSUBSCRIBE;
2336  UnregisterTable(table);
2337  return true;
2338  }
2339 
2340  string vrf_name = table->routing_instance()->name();
2341  VrfTableName vrf_n_table = make_pair(vrf_name, table->name());
2342 
2343  if (tmr_state->pending_req == UNSUBSCRIBE) {
2344  if (!GetInstanceMembershipState(vrf_name))
2345  assert(defer_q_.count(vrf_n_table) == 0);
2346  DeleteTableMembershipState(table_name);
2347  return true;
2348  } else if (tmr_state->pending_req == SUBSCRIBE) {
2349  mgr->SetRegistrationInfo(peer_.get(), table, tmr_state->instance_id,
2351  DeleteTableMembershipState(table_name);
2352  }
2353 
2354  for (DeferQ::iterator it = defer_q_.find(vrf_n_table);
2355  it != defer_q_.end() && it->first.second == table->name(); ++it) {
2356  DequeueRequest(table->name(), it->second);
2357  }
2358 
2359  // Erase all elements for the table
2360  defer_q_.erase(vrf_n_table);
2361 
2362  return true;
2363 }
2364 
2367 }
2368 
2369 void BgpXmppChannel::FillCloseInfo(BgpNeighborResp *resp) const {
2370  close_manager_->FillCloseInfo(resp);
2371 }
2372 
2373 void BgpXmppChannel::FillInstanceMembershipInfo(BgpNeighborResp *resp) const {
2374  vector<BgpNeighborRoutingInstance> instance_list;
2375  BOOST_FOREACH(const SubscribedRoutingInstanceList::value_type &entry,
2377  BgpNeighborRoutingInstance instance;
2378  instance.set_name(entry.first->name());
2379  if (entry.second.IsLlgrStale()) {
2380  instance.set_state("subscribed-llgr-stale");
2381  } else if (entry.second.IsGrStale()) {
2382  instance.set_state("subscribed-gr-stale");
2383  } else {
2384  instance.set_state("subscribed");
2385  }
2386  instance.set_index(entry.second.index);
2387  rtarget_manager_->FillInfo(&instance, entry.second.targets);
2388  instance_list.push_back(instance);
2389  }
2390  BOOST_FOREACH(const InstanceMembershipRequestMap::value_type &entry,
2392  const InstanceMembershipRequestState &imr_state = entry.second;
2393  BgpNeighborRoutingInstance instance;
2394  instance.set_name(entry.first);
2395  instance.set_state("pending");
2396  instance.set_index(imr_state.instance_id);
2397  instance_list.push_back(instance);
2398  }
2399  resp->set_routing_instances(instance_list);
2400 }
2401 
2402 void BgpXmppChannel::FillTableMembershipInfo(BgpNeighborResp *resp) const {
2403  vector<BgpNeighborRoutingTable> old_table_list = resp->get_routing_tables();
2404  set<string> old_table_set;
2405  vector<BgpNeighborRoutingTable> new_table_list;
2406 
2407  BOOST_FOREACH(const BgpNeighborRoutingTable &table, old_table_list) {
2408  old_table_set.insert(table.get_name());
2409  if (!GetTableMembershipState(table.get_name()))
2410  new_table_list.push_back(table);
2411  }
2412 
2413  BOOST_FOREACH(const TableMembershipRequestMap::value_type &entry,
2415  BgpNeighborRoutingTable table;
2416  table.set_name(entry.first);
2417  if (old_table_set.find(entry.first) != old_table_set.end())
2418  table.set_current_state("subscribed");
2419  const TableMembershipRequestState &tmr_state = entry.second;
2420  if (tmr_state.current_req == SUBSCRIBE) {
2421  table.set_current_request("subscribe");
2422  } else {
2423  table.set_current_request("unsubscribe");
2424  }
2425  if (tmr_state.pending_req == SUBSCRIBE) {
2426  table.set_pending_request("subscribe");
2427  } else {
2428  table.set_pending_request("unsubscribe");
2429  }
2430  new_table_list.push_back(table);
2431  }
2432  resp->set_routing_tables(new_table_list);
2433 }
2434 
2435 //
2436 // Erase all defer_q_ elements with the given (vrf, table).
2437 //
2438 void BgpXmppChannel::FlushDeferQ(string vrf_name, string table_name) {
2439  for (DeferQ::iterator it =
2440  defer_q_.find(make_pair(vrf_name, table_name)), itnext;
2441  (it != defer_q_.end() && it->first.second == table_name);
2442  it = itnext) {
2443  itnext = it;
2444  itnext++;
2445  delete it->second;
2446  defer_q_.erase(it);
2447  }
2448 }
2449 
2450 //
2451 // Erase all defer_q_ elements for all tables for the given vrf.
2452 //
2453 void BgpXmppChannel::FlushDeferQ(string vrf_name) {
2454  for (DeferQ::iterator it =
2455  defer_q_.lower_bound(make_pair(vrf_name, string())), itnext;
2456  (it != defer_q_.end() && it->first.first == vrf_name);
2457  it = itnext) {
2458  itnext = it;
2459  itnext++;
2460  delete it->second;
2461  defer_q_.erase(it);
2462  }
2463 }
2464 
2465 // Mark all current subscriptions as 'stale'. This is called when peer close
2466 // process is initiated by BgpXmppChannel via PeerCloseManager.
2468  CHECK_CONCURRENCY(peer_close_->GetTaskName());
2469  BOOST_FOREACH(SubscribedRoutingInstanceList::value_type &entry,
2471  entry.second.SetGrStale();
2472  rtarget_manager_->UpdateRouteTargetRouteFlag(entry.first,
2473  entry.second.targets, BgpPath::Stale);
2474  }
2475 }
2476 
2477 // Mark all current subscriptions as 'llgr_stale'.
2479  CHECK_CONCURRENCY(peer_close_->GetTaskName());
2480  BOOST_FOREACH(SubscribedRoutingInstanceList::value_type &entry,
2482  assert(entry.second.IsGrStale());
2483  entry.second.SetLlgrStale();
2484  rtarget_manager_->UpdateRouteTargetRouteFlag(entry.first,
2485  entry.second.targets, BgpPath::Stale | BgpPath::LlgrStale);
2486  }
2487 }
2488 
2489 // Sweep all current subscriptions which are still marked as 'stale'.
2491  CHECK_CONCURRENCY(peer_close_->GetTaskName());
2492  for (SubscribedRoutingInstanceList::iterator i = routing_instances_.begin();
2493  i != routing_instances_.end();) {
2494  if (i->second.IsGrStale()) {
2495  string name = i->first->name();
2496 
2497  // Increment the iterator first as we expect the entry to be
2498  // soon removed.
2499  i++;
2500  BGP_LOG_PEER(Membership, Peer(), SandeshLevel::SYS_DEBUG,
2502  "Instance subscription " << name <<
2503  " is still stale and hence unsubscribed");
2504  ProcessSubscriptionRequest(name, NULL, false);
2505  } else {
2506  i++;
2507  }
2508  }
2509 }
2510 
2511 // Clear staled subscription state as new subscription has been received.
2513  SubscriptionState *sub_state) {
2514  if (!sub_state->IsGrStale())
2515  return;
2516 
2517  BGP_LOG_PEER(Membership, Peer(), SandeshLevel::SYS_DEBUG,
2519  "Instance subscription " << rt_instance->name() <<
2520  " stale flag is cleared");
2521  sub_state->ClearStale();
2522  rtarget_manager_->Stale(sub_state->targets);
2523 }
2524 
2526  int index) {
2527  SubscriptionState state(rt_instance->GetImportList(), index);
2528  pair<SubscribedRoutingInstanceList::iterator, bool> ret =
2529  routing_instances_.insert(pair<RoutingInstance *, SubscriptionState> (
2530  rt_instance, state));
2531 
2532  // During GR, we expect duplicate subscription requests. Clear stale
2533  // state, as agent did re-subscribe after restart.
2534  if (!ret.second) {
2535  ClearStaledSubscription(rt_instance, &ret.first->second);
2536  } else {
2537  rtarget_manager_->PublishRTargetRoute(rt_instance, true);
2538  }
2539 }
2540 
2542  routing_instances_.erase(rt_instance);
2543 }
2544 
2546  RoutingInstance *rt_instance) {
2547  SubscribedRoutingInstanceList::iterator loc =
2548  routing_instances_.find(rt_instance);
2549  return (loc != routing_instances_.end() ? &loc->second : NULL);
2550 }
2551 
2553  RoutingInstance *rt_instance) const {
2554  SubscribedRoutingInstanceList::const_iterator loc =
2555  routing_instances_.find(rt_instance);
2556  return (loc != routing_instances_.end() ? &loc->second : NULL);
2557 }
2558 
2560  const InstanceMembershipRequestState &imr_state) {
2561  int instance_id = imr_state.instance_id;
2562  bool no_ribout = imr_state.no_ribout;
2563  AddSubscriptionState(instance, instance_id);
2564  RoutingInstance::RouteTableList const rt_list = instance->GetTables();
2565  for (RoutingInstance::RouteTableList::const_iterator it = rt_list.begin();
2566  it != rt_list.end(); ++it) {
2567  BgpTable *table = it->second;
2568  if (table->IsVpnTable() || table->family() == Address::RTARGET)
2569  continue;
2570 
2571  TableMembershipRequestState tmr_state(
2572  SUBSCRIBE, instance_id, no_ribout);
2573  AddTableMembershipState(table->name(), tmr_state);
2574  RegisterTable(table, &tmr_state);
2575  }
2576 }
2577 
2579  string vrf_name, const XmppStanza::XmppMessageIq *iq,
2580  bool add_change) {
2581  int instance_id = -1;
2582  bool no_ribout = false;
2583 
2584  if (add_change) {
2585  XmlPugi *pugi = reinterpret_cast<XmlPugi *>(iq->dom.get());
2586  xml_node options = pugi->FindNode("options");
2587  for (xml_node node = options.first_child(); node;
2588  node = node.next_sibling()) {
2589  if (strcmp(node.name(), "instance-id") == 0) {
2590  instance_id = node.text().as_int();
2591  }
2592  if (strcmp(node.name(), "no-ribout") == 0) {
2593  no_ribout = node.text().as_bool();
2594  }
2595  }
2596  }
2597 
2599  assert(instance_mgr);
2600  RoutingInstance *rt_instance = instance_mgr->GetRoutingInstance(vrf_name);
2601  if (rt_instance == NULL) {
2602  BGP_LOG_PEER(Membership, Peer(), SandeshLevel::SYS_INFO,
2604  "Routing instance " << vrf_name <<
2605  " not found when processing " <<
2606  (add_change ? "subscribe" : "unsubscribe"));
2607  if (add_change) {
2608  if (GetInstanceMembershipState(vrf_name)) {
2609  BGP_LOG_PEER_WARNING(Membership, Peer(),
2611  "Duplicate subscribe for routing instance " <<
2612  vrf_name << ", triggering close");
2613  channel_->Close();
2614  } else {
2615  AddInstanceMembershipState(vrf_name,
2616  InstanceMembershipRequestState(instance_id, no_ribout));
2618  }
2619  } else {
2620  if (DeleteInstanceMembershipState(vrf_name)) {
2621  FlushDeferQ(vrf_name);
2623  } else {
2624  BGP_LOG_PEER_WARNING(Membership, Peer(),
2626  "Spurious unsubscribe for routing instance " <<
2627  vrf_name << ", triggering close");
2628  channel_->Close();
2629  }
2630  }
2631  return;
2632  } else if (rt_instance->deleted()) {
2633  BGP_LOG_PEER(Membership, Peer(), SandeshLevel::SYS_DEBUG,
2635  "Routing instance " << vrf_name <<
2636  " is being deleted when processing " <<
2637  (add_change ? "subscribe" : "unsubscribe"));
2638  if (add_change) {
2639  if (GetInstanceMembershipState(vrf_name)) {
2640  BGP_LOG_PEER_WARNING(Membership, Peer(),
2642  "Duplicate subscribe for routing instance " <<
2643  vrf_name << ", triggering close");
2644  channel_->Close();
2645  } else if (GetSubscriptionState(rt_instance)) {
2646  BGP_LOG_PEER_WARNING(Membership, Peer(),
2648  "Duplicate subscribe for routing instance " <<
2649  vrf_name << ", triggering close");
2650  channel_->Close();
2651  } else {
2652  AddInstanceMembershipState(vrf_name,
2653  InstanceMembershipRequestState(instance_id, no_ribout));
2655  }
2656  return;
2657  } else {
2658  // If instance is being deleted and agent is trying to unsubscribe
2659  // we need to process the unsubscribe if vrf is not in the request
2660  // map. This would be the normal case where we wait for agent to
2661  // unsubscribe in order to remove routes added by it.
2662  if (DeleteInstanceMembershipState(vrf_name)) {
2663  FlushDeferQ(vrf_name);
2665  return;
2666  } else if (!GetSubscriptionState(rt_instance)) {
2667  BGP_LOG_PEER_WARNING(Membership, Peer(),
2669  "Spurious unsubscribe for routing instance " <<
2670  vrf_name << ", triggering close");
2671  channel_->Close();
2672  return;
2673  }
2675  }
2676  } else {
2677  if (add_change) {
2678  const SubscriptionState *sub_state =
2679  GetSubscriptionState(rt_instance);
2680  if (sub_state) {
2681  if (!close_manager_->IsCloseInProgress()) {
2682  BGP_LOG_PEER_WARNING(Membership, Peer(),
2684  "Duplicate subscribe for routing instance " <<
2685  vrf_name << ", triggering close");
2686  channel_->Close();
2687  return;
2688  }
2689  if (!sub_state->IsGrStale()) {
2690  BGP_LOG_PEER_WARNING(Membership, Peer(),
2692  "Duplicate subscribe for routing instance " <<
2693  vrf_name << " under GR, triggering close");
2694  channel_->Close();
2695  return;
2696  }
2697  }
2699  } else {
2700  if (!GetSubscriptionState(rt_instance)) {
2701  BGP_LOG_PEER_WARNING(Membership, Peer(),
2703  "Spurious unsubscribe for routing instance " <<
2704  vrf_name << ", triggering close");
2705  channel_->Close();
2706  return;
2707  }
2709  }
2710  }
2711 
2712  if (add_change) {
2713  AddSubscriptionState(rt_instance, instance_id);
2714  } else {
2715  rtarget_manager_->PublishRTargetRoute(rt_instance, false);
2716  DeleteSubscriptionState(rt_instance);
2717  }
2718 
2719  RoutingInstance::RouteTableList const rt_list = rt_instance->GetTables();
2720  for (RoutingInstance::RouteTableList::const_iterator it = rt_list.begin();
2721  it != rt_list.end(); ++it) {
2722  BgpTable *table = it->second;
2723  if (table->IsVpnTable() || table->family() == Address::RTARGET)
2724  continue;
2725 
2726  if (add_change) {
2727  TableMembershipRequestState *tmr_state =
2728  GetTableMembershipState(table->name());
2729  if (!tmr_state) {
2730  TableMembershipRequestState tmp_tmr_state(
2731  SUBSCRIBE, instance_id, no_ribout);
2732  AddTableMembershipState(table->name(), tmp_tmr_state);
2733  RegisterTable(table, &tmp_tmr_state);
2734  } else {
2735  tmr_state->instance_id = instance_id;
2736  tmr_state->pending_req = SUBSCRIBE;
2737  tmr_state->no_ribout = no_ribout;
2738  }
2739  } else {
2740  if (defer_q_.count(make_pair(vrf_name, table->name()))) {
2741  BGP_LOG_PEER(Membership, Peer(), SandeshLevel::SYS_DEBUG,
2743  "Flush deferred route requests for table " <<
2744  table->name() << " on unsubscribe");
2745  FlushDeferQ(vrf_name, table->name());
2746  }
2747 
2748  // Erase all elements for the table.
2749 
2750  TableMembershipRequestState *tmr_state =
2751  GetTableMembershipState(table->name());
2752  if (!tmr_state) {
2753  AddTableMembershipState(table->name(),
2755  UNSUBSCRIBE, instance_id, no_ribout));
2756  UnregisterTable(table);
2757  } else {
2758  tmr_state->instance_id = -1;
2759  tmr_state->pending_req = UNSUBSCRIBE;
2760  tmr_state->no_ribout = false;
2761  }
2762  }
2763  }
2764 }
2765 
2769  eor_sent_ = false;
2770 }
2771 
2774  close_manager_->ProcessEORMarkerReceived(family);
2775 }
2776 
2778  string error_message) {
2780  "Timer error: " << error_name << " " << error_message);
2781 }
2782 
2784  if (!peer_->IsReady())
2785  return false;
2786 
2787  uint32_t timeout = manager() && manager()->xmpp_server() ?
2790 
2791  // If max timeout has not reached yet, check if we can exit GR sooner by
2792  // looking at the activity in the channel.
2793  if (UTCTimestamp() - eor_receive_timer_start_time_ < timeout) {
2794 
2795  // If there is some send or receive activity in the channel in last few
2796  // seconds, delay EoR receive event.
2800  BGP_LOG_PEER(Message, Peer(), SandeshLevel::SYS_INFO,
2802  "EndOfRib Receive timer rescheduled to fire after " <<
2803  kEndOfRibSendRetryTime << " second(s)");
2804  return true;
2805  }
2806  }
2807 
2808  BGP_LOG_PEER(Message, Peer(), SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
2809  BGP_PEER_DIR_IN, "EndOfRib Receive timer expired");
2811  return false;
2812 }
2813 
2815  return manager() && manager()->xmpp_server() ?
2818 }
2819 
2821  if (!peer_->IsReady())
2822  return false;
2823 
2824  // If max timeout has not reached yet, check if we can exit GR sooner by
2825  // looking at the activity in the channel.
2827 
2828  // If there is some send or receive activity in the channel in last few
2829  // seconds, delay EoR send event.
2832  manager()->bgp_server()->IsServerStartingUp()) {
2834  BGP_LOG_PEER(Message, Peer(), SandeshLevel::SYS_INFO,
2836  "EndOfRib Send timer rescheduled to fire after " <<
2837  kEndOfRibSendRetryTime << " second(s)");
2838  return true;
2839  }
2840  }
2841 
2842  SendEndOfRIB();
2843  return false;
2844 }
2845 
2847  uint32_t timeout = manager() && manager()->xmpp_server() ?
2852 
2853  BGP_LOG_PEER(Message, Peer(), SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
2854  BGP_PEER_DIR_IN, "EndOfRib Receive timer scheduled to fire after " <<
2855  timeout << " second(s)");
2856  eor_receive_timer_->Start(timeout * 1000,
2857  boost::bind(&BgpXmppChannel::EndOfRibReceiveTimerExpired, this),
2858  boost::bind(&BgpXmppChannel::EndOfRibTimerErrorHandler, this, _1, _2));
2859 }
2860 
2862  if (eor_sent_)
2863  return;
2864 
2865  // If socket is blocked, then wait for it to get unblocked first.
2866  if (!peer_->send_ready())
2867  return;
2868 
2869  // If there is any outstanding subscribe pending, wait for its completion.
2872  return;
2873 
2876 
2877  BGP_LOG_PEER(Message, Peer(), SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
2878  BGP_PEER_DIR_OUT, "EndOfRib Send timer scheduled to fire after " <<
2879  kEndOfRibSendRetryTime << " second(s)");
2881  boost::bind(&BgpXmppChannel::EndOfRibSendTimerExpired, this),
2882  boost::bind(&BgpXmppChannel::EndOfRibTimerErrorHandler, this, _1, _2));
2883 }
2884 
2885 /*
2886  * Empty items list constitute eor marker.
2887  */
2890  eor_sent_ = true;
2891 
2892  string msg;
2893  msg += "\n<message from=\"";
2895  msg += "\" to=\"";
2896  msg += peer_->ToString();
2897  msg += "/";
2898  msg += XmppInit::kBgpPeer;
2899  msg += "\">";
2900  msg += "\n\t<event xmlns=\"http://jabber.org/protocol/pubsub\">";
2901  msg = (msg + "\n<items node=\"") + XmppInit::kEndOfRibMarker +
2902  "\"></items>";
2903  msg += "\n\t</event>\n</message>\n";
2904 
2905  if (channel_->connection())
2906  channel_->connection()->Send((const uint8_t *) msg.data(), msg.size());
2907 
2908  stats_[TX].end_of_rib++;
2909  BGP_LOG_PEER(Message, Peer(), SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
2910  BGP_PEER_DIR_OUT, "EndOfRib marker sent");
2911 }
2912 
2913 // Process any associated primary instance-id.
2915  bool expect_prefix_len) const {
2916  if (s.empty())
2917  return 0;
2918  char *str = const_cast<char *>(s.c_str());
2919  char *saveptr, *token;
2920  token = strtok_r(str, "/", &saveptr); // Get afi
2921  if (!token || !saveptr)
2922  return 0;
2923  token = strtok_r(NULL, "/", &saveptr); // Get safi
2924  if (!token || !saveptr)
2925  return 0;
2926  token = strtok_r(NULL, "/", &saveptr); // vrf name
2927  if (!token || !saveptr)
2928  return 0;
2929  token = strtok_r(NULL, "/", &saveptr); // address
2930  if (!token || !saveptr)
2931  return 0;
2932  if (expect_prefix_len) {
2933  token = strtok_r(NULL, "/", &saveptr); // prefix-length
2934  if (!token || !saveptr)
2935  return 0;
2936  }
2937  token = strtok_r(NULL, "/", &saveptr); // primary instance-id
2938  if (!token)
2939  return 0;
2940  return strtoul(token, NULL, 0);
2941 }
2942 
2944  CHECK_CONCURRENCY("xmpp::StateMachine");
2945 
2946  // Bail if the connection is being deleted. It's not safe to assert
2947  // because the Delete method can be called from the main thread.
2949  return;
2950 
2951  // Make sure that peer is not set for closure already.
2952  assert(!defer_peer_close_);
2953  assert(!peer_deleted());
2954 
2955  if (msg->type == XmppStanza::IQ_STANZA) {
2956  const XmppStanza::XmppMessageIq *iq =
2957  static_cast<const XmppStanza::XmppMessageIq *>(msg);
2958  if (iq->iq_type.compare("set") == 0) {
2959  if (iq->action.compare("subscribe") == 0) {
2960  ProcessSubscriptionRequest(iq->node, iq, true);
2961  } else if (iq->action.compare("unsubscribe") == 0) {
2962  ProcessSubscriptionRequest(iq->node, iq, false);
2963  } else if (iq->action.compare("publish") == 0) {
2964  XmlBase *impl = msg->dom.get();
2965  stats_[RX].rt_updates++;
2966  XmlPugi *pugi = reinterpret_cast<XmlPugi *>(impl);
2967  xml_node item = pugi->FindNode("item");
2968 
2969  // Empty items-list can be considered as EOR Marker for all afis
2970  if (item == 0) {
2971  BGP_LOG_PEER(Message, Peer(), SandeshLevel::SYS_INFO,
2973  "EndOfRib marker received");
2974  stats_[RX].end_of_rib++;
2976  return;
2977  }
2978  for (; item; item = item.next_sibling()) {
2979  if (strcmp(item.name(), "item") != 0) continue;
2980 
2981  string id(iq->as_node.c_str());
2982  char *str = const_cast<char *>(id.c_str());
2983  char *saveptr;
2984  char *af = strtok_r(str, "/", &saveptr);
2985  char *safi = strtok_r(NULL, "/", &saveptr);
2986 
2987  if (atoi(af) == BgpAf::IPv4 &&
2988  ((atoi(safi) == BgpAf::Unicast) ||
2989  (atoi(safi) == BgpAf::Mpls))) {
2990  ProcessItem(iq->node, item, iq->is_as_node,
2991  GetPrimaryInstanceID(iq->as_node, true));
2992  } else if (atoi(af) == BgpAf::IPv6 &&
2993  atoi(safi) == BgpAf::Unicast) {
2994  ProcessInet6Item(iq->node, item, iq->is_as_node);
2995  } else if (atoi(af) == BgpAf::IPv4 &&
2996  atoi(safi) == BgpAf::Mcast) {
2997  ProcessMcastItem(iq->node, item, iq->is_as_node);
2998  } else if (atoi(af) == BgpAf::IPv4 &&
2999  atoi(safi) == BgpAf::MVpn) {
3000  ProcessMvpnItem(iq->node, item, iq->is_as_node);
3001  } else if (atoi(af) == BgpAf::L2Vpn &&
3002  atoi(safi) == BgpAf::Enet) {
3003  ProcessEnetItem(iq->node, item, iq->is_as_node);
3004  }
3005  }
3006  }
3007  }
3008  }
3009 }
3010 
3012  if (!channel->deleted()) {
3013  channel->set_deleted(true);
3014  delete channel;
3015  }
3016  return true;
3017 }
3018 
3019 // BgpXmppChannelManager routines.
3021  BgpServer *server)
3022  : xmpp_server_(xmpp_server),
3023  bgp_server_(server),
3024  queue_(TaskScheduler::GetInstance()->GetTaskId("bgp::Config"), 0,
3025  boost::bind(&BgpXmppChannelManager::DeleteChannel, this, _1)),
3026  id_(-1),
3027  asn_listener_id_(-1),
3028  identifier_listener_id_(-1),
3029  dscp_listener_id_(-1) {
3030  // Initialize the gen id counter
3032  deleting_count_ = 0;
3033 
3034  if (xmpp_server)
3037  boost::bind(&BgpXmppChannelManager::IsReadyForDeletion, this));
3038  if (xmpp_server) {
3041  this, _1, _2));
3042  }
3044  server->RegisterAdminDownCallback(boost::bind(
3047  server->RegisterASNUpdateCallback(boost::bind(
3050  server->RegisterIdentifierUpdateCallback(boost::bind(
3053  server->RegisterDSCPUpdateCallback(boost::bind(
3055 
3058  this, _1, _2));
3059 }
3060 
3062  assert(channel_map_.empty());
3063  assert(channel_name_map_.empty());
3064  assert(deleting_count_ == 0);
3065  if (xmpp_server_) {
3067  }
3068 
3069  queue_.Shutdown();
3074 }
3075 
3077  return bgp_server_->IsReadyForDeletion();
3078 }
3079 
3081  queue_.set_disable(disabled);
3082 }
3083 
3085  return queue_.Length();
3086 }
3087 
3090 }
3091 
3093  xmpp_server_->SetDscpValue(dscp_value);
3094 }
3095 
3097  as_t old_local_asn) {
3098  CHECK_CONCURRENCY("bgp::Config");
3099  BOOST_FOREACH(XmppChannelMap::value_type &i, channel_map_) {
3100  i.second->rtarget_manager()->ASNUpdateCallback(old_asn, old_local_asn);
3101  }
3102  if (bgp_server_->autonomous_system() != old_asn) {
3104  }
3105 }
3106 
3108  Ip4Address old_identifier) {
3109  CHECK_CONCURRENCY("bgp::Config");
3111 }
3112 
3113 void BgpXmppChannelManager::RoutingInstanceCallback(string vrf_name, int op) {
3114  CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
3115  BOOST_FOREACH(XmppChannelMap::value_type &i, channel_map_) {
3116  i.second->RoutingInstanceCallback(vrf_name, op);
3117  }
3118 }
3119 
3121  std::scoped_lock lock(mutex_);
3122  BOOST_FOREACH(XmppChannelMap::value_type &i, channel_map_) {
3123  fn(i.second);
3124  }
3125 }
3126 
3128  const {
3129  std::scoped_lock lock(mutex_);
3130  BOOST_FOREACH(const XmppChannelMap::value_type &i, channel_map_) {
3131  fn(i.second);
3132  }
3133 }
3134 
3136  BOOST_FOREACH(XmppChannelMap::value_type &i, channel_map_) {
3137  if (i.second->ToString() == client) {
3138  return i.second;
3139  }
3140  }
3141  return NULL;
3142 }
3143 
3145  const XmppChannel *ch) {
3146  XmppChannelMap::iterator it = channel_map_.find(ch);
3147  if (it == channel_map_.end())
3148  return NULL;
3149  return it->second;
3150 }
3151 
3153  if (channel->connection() && !channel->connection()->IsActiveChannel()) {
3154  CHECK_CONCURRENCY("bgp::Config");
3155  }
3156  channel_map_.erase(channel);
3157  channel_name_map_.erase(channel->ToString());
3158 }
3159 
3161  CHECK_CONCURRENCY("xmpp::StateMachine");
3162  BgpXmppChannel *ch = new BgpXmppChannel(channel, bgp_server_, this);
3163 
3164  return ch;
3165 }
3166 
3168  xmps::PeerState state) {
3169  std::scoped_lock lock(mutex_);
3170 
3171  XmppChannelMap::iterator it = channel_map_.find(channel);
3172  BgpXmppChannel *bgp_xmpp_channel = NULL;
3173  if (state == xmps::READY) {
3174  if (it == channel_map_.end()) {
3175  bgp_xmpp_channel = CreateChannel(channel);
3176  channel_map_.insert(make_pair(channel, bgp_xmpp_channel));
3177  channel_name_map_.insert(
3178  make_pair(channel->ToString(), bgp_xmpp_channel));
3179  BGP_LOG_PEER(Message, bgp_xmpp_channel->Peer(),
3182  "Received XmppChannel up event");
3184  BGP_LOG_PEER(Message, bgp_xmpp_channel->Peer(),
3185  SandeshLevel::SYS_INFO, BGP_LOG_FLAG_SYSLOG,
3187  "No BGP configuration for self - closing channel");
3188  if (!getenv("CONTRAIL_CAT_FRAMEWORK"))
3189  channel->Close();
3190  }
3191  if (bgp_server_->admin_down()) {
3192  BGP_LOG_PEER(Message, bgp_xmpp_channel->Peer(),
3193  SandeshLevel::SYS_INFO, BGP_LOG_FLAG_SYSLOG,
3195  "BGP is administratively down - closing channel");
3196  channel->Close();
3197  }
3198  } else {
3199  bgp_xmpp_channel = (*it).second;
3200  if (bgp_xmpp_channel->peer_deleted())
3201  return;
3202 
3203  // Gracefully close the channel if GR closure is in progress.
3204  // This can happen if GR timers fire just after session comes
3205  // back up.
3206  if (bgp_xmpp_channel->close_manager()->IsCloseInProgress() &&
3207  !bgp_xmpp_channel->close_manager()->IsInGRTimerWaitState()) {
3208  BGP_LOG_PEER(Message, bgp_xmpp_channel->Peer(),
3209  SandeshLevel::SYS_INFO, BGP_LOG_FLAG_SYSLOG,
3211  "Graceful Closure in progress - Closing channel");
3212  channel->Close();
3213  }
3214  channel->RegisterReceive(xmps::BGP,
3215  boost::bind(&BgpXmppChannel::ReceiveUpdate, bgp_xmpp_channel,
3216  _1));
3217  }
3218 
3219  bgp_xmpp_channel->eor_sent_ = false;
3220  bgp_xmpp_channel->StartEndOfRibReceiveTimer();
3221  bgp_xmpp_channel->ResetEndOfRibSendState();
3222  } else if (state == xmps::NOT_READY) {
3223  if (it != channel_map_.end()) {
3224  bgp_xmpp_channel = (*it).second;
3225  BGP_LOG_PEER(Message, bgp_xmpp_channel->Peer(),
3228  "Received XmppChannel down event");
3229 
3230  // Trigger closure of this channel
3231  bgp_xmpp_channel->Close();
3232  } else {
3233  ostringstream os;
3234  os << "Peer not found for " << channel->ToString() <<
3235  " on channel down event";
3237  }
3238  }
3239 }
3240 
3242  PeerStatsInfo stats;
3243  PeerStats::FillPeerDebugStats(channel->Peer()->peer_stats(), &stats);
3244 
3245  XmppPeerInfoData peer_info;
3246  peer_info.set_name(channel->Peer()->ToUVEKey());
3247  peer_info.set_peer_stats_info(stats);
3248  assert(!peer_info.get_name().empty());
3249  BGP_UVE_SEND(XMPPPeerInfo, peer_info);
3250 
3251  PeerStatsData peer_stats_data;
3252  peer_stats_data.set_name(channel->Peer()->ToUVEKey());
3253  peer_stats_data.set_encoding("XMPP");
3255  &peer_stats_data);
3256  assert(!peer_stats_data.get_name().empty());
3257  BGP_UVE_SEND2(PeerStatsUve, peer_stats_data, "ObjectXmppPeerInfo");
3258 }
3259 
3260 bool BgpXmppChannelManager::CollectStats(BgpRouterState *state, bool first)
3261  const {
3262  CHECK_CONCURRENCY("bgp::ShowCommand");
3263 
3264  VisitChannels(boost::bind(&BgpXmppChannelManager::FillPeerInfo, this, _1));
3265  bool change = false;
3266  uint32_t num_xmpp = count();
3267  if (first || num_xmpp != state->get_num_xmpp_peer()) {
3268  state->set_num_xmpp_peer(num_xmpp);
3269  change = true;
3270  }
3271 
3272  uint32_t num_up_xmpp = NumUpPeer();
3273  if (first || num_up_xmpp != state->get_num_up_xmpp_peer()) {
3274  state->set_num_up_xmpp_peer(num_up_xmpp);
3275  change = true;
3276  }
3277 
3278  uint32_t num_deleting_xmpp = deleting_count();
3279  if (first || num_deleting_xmpp != state->get_num_deleting_xmpp_peer()) {
3280  state->set_num_deleting_xmpp_peer(num_deleting_xmpp);
3281  change = true;
3282  }
3283 
3284  return change;
3285 }
3286 
3290 
3291  if (table_membership_requests()) {
3292  BGP_LOG_PEER(Event, peer_.get(), SandeshLevel::SYS_INFO,
3293  BGP_LOG_FLAG_ALL, BGP_PEER_DIR_NA, "Close procedure deferred");
3294  defer_peer_close_ = true;
3295  return;
3296  }
3297  peer_->Close(true);
3298 }
3299 
3300 //
3301 // Return connection's remote tcp endpoint if available
3302 //
3304  const XmppSession *session = GetSession();
3305  if (session) {
3306  return session->remote_endpoint();
3307  }
3308  return TcpSession::Endpoint();
3309 }
3310 
3311 //
3312 // Return connection's local tcp endpoint if available
3313 //
3315  const XmppSession *session = GetSession();
3316  if (session) {
3317  return session->local_endpoint();
3318  }
3319  return TcpSession::Endpoint();
3320 }
3321 
3322 //
3323 // Return connection's remote tcp endpoint string.
3324 //
3327  ostringstream oss;
3328  oss << endpoint;
3329  return oss.str();
3330 }
3331 
3332 //
3333 // Mark the XmppPeer as deleted.
3334 //
3336  peer_->SetPeerClosed(flag);
3337 }
3338 
3339 //
3340 // Return true if the XmppPeer is deleted.
3341 //
3343  return peer_->IsDeleted();
3344 }
3345 
3346 //
3347 // Return time stamp of when the XmppPeer delete was initiated.
3348 //
3350  return peer_->closed_at();
3351 }
3352 
3354  SubscribedRoutingInstanceList::const_iterator it =
3355  routing_instances_.find(instance);
3356  assert(it != routing_instances_.end());
3357  return it->second.IsGrStale();
3358 }
3359 
3361  SubscribedRoutingInstanceList::const_iterator it =
3362  routing_instances_.find(instance);
3363  assert(it != routing_instances_.end());
3364  return it->second.IsLlgrStale();
3365 }
3366 
3368  return routing_instances_.empty();
3369 }
3370 
3372  RoutingInstance *instance) const {
3373  SubscribedRoutingInstanceList::const_iterator it =
3374  routing_instances_.find(instance);
3375  assert(it != routing_instances_.end());
3376  return it->second.targets;
3377 }
boost::asio::ip::address IpAddress
Definition: address.h:14
boost::asio::ip::address_v4 Ip4Address
Definition: address.h:15
std::vector< BgpAttribute * > BgpAttrSpec
Definition: bgp_attr.h:823
boost::intrusive_ptr< const BgpAttr > BgpAttrPtr
Definition: bgp_attr.h:999
#define AS2_MAX
Definition: bgp_common.h:25
uint32_t as_t
Definition: bgp_common.h:22
#define BGP_LOG_NOTICE(obj, flags,...)
Definition: bgp_log.h:74
#define BGP_LOG_FLAG_ALL
Definition: bgp_log.h:45
#define BGP_LOG_FLAG_SYSLOG
Definition: bgp_log.h:43
#define BGP_LOG_PEER(type, peer, level, flags, dir, arg)
Definition: bgp_log.h:160
#define BGP_LOG_PEER_INSTANCE_WARNING(peer, instance, flags, arg)
Definition: bgp_log.h:228
#define BGP_LOG_PEER_INSTANCE(peer, instance, level, flags, arg)
Definition: bgp_log.h:219
#define BGP_LOG_PEER_WARNING(type, peer, flags, dir, arg)
Definition: bgp_log.h:183
#define BGP_PEER_DIR_IN
Definition: bgp_log.h:140
#define BGP_LOG_PEER_TABLE(peer, level, flags, tbl, arg)
Definition: bgp_log.h:206
#define BGP_UVE_SEND2(type, object, arg)
Definition: bgp_log.h:53
#define BGP_PEER_DIR_NA
Definition: bgp_log.h:141
#define BGP_LOG_FLAG_TRACE
Definition: bgp_log.h:44
#define BGP_UVE_SEND(type, object)
Definition: bgp_log.h:47
#define BGP_LOG_PEER_CRITICAL(type, peer, flags, dir, arg)
Definition: bgp_log.h:195
#define BGP_LOG_PEER_INSTANCE_CRITICAL(peer, instance, dir, flags, arg)
Definition: bgp_log.h:238
#define BGP_PEER_DIR_OUT
Definition: bgp_log.h:139
static uint32_t GetMedFromLocalPref(uint32_t local_pref)
Family
Definition: address.h:25
@ EVPN
Definition: address.h:32
@ RTARGET
Definition: address.h:31
@ ERMVPN
Definition: address.h:33
@ INET6
Definition: address.h:28
@ MVPN
Definition: address.h:34
@ INETMPLS
Definition: address.h:35
@ UNSPEC
Definition: address.h:26
@ Enet
Definition: bgp_af.h:33
@ Unicast
Definition: bgp_af.h:26
@ MVpn
Definition: bgp_af.h:28
@ Mcast
Definition: bgp_af.h:32
@ Mpls
Definition: bgp_af.h:27
@ L2Vpn
Definition: bgp_af.h:22
@ IPv4
Definition: bgp_af.h:20
@ IPv6
Definition: bgp_af.h:21
static Address::Family AfiSafiToFamily(uint16_t afi, uint8_t safi)
Definition: bgp_af.cc:72
static const char * kMasterInstance
Definition: bgp_config.h:779
uint16_t rd_cluster_seed() const
Definition: bgp_config.h:671
static const int kEndOfRibTime
Definition: bgp_config.h:616
void SetRegistrationInfo(const IPeer *peer, const BgpTable *table, int instance_id, uint64_t subscription_gen_id)
void RegisterRibIn(IPeer *peer, BgpTable *table)
virtual void Unregister(IPeer *peer, BgpTable *table)
virtual void Register(IPeer *peer, BgpTable *table, const RibExportPolicy &policy, int instance_id=-1)
bool GetRegistrationInfo(const IPeer *peer, const BgpTable *table, int *instance_id=NULL, uint64_t *subscription_gen_id=NULL) const
bool IsRibOutRegistered(const IPeer *peer, const BgpTable *table) const
TypePtr Locate(Type *attr)
@ Stale
Definition: bgp_path.h:25
@ LlgrStale
Definition: bgp_path.h:31
@ CheckGlobalErmVpnRoute
Definition: bgp_path.h:34
@ ResolveNexthop
Definition: bgp_path.h:28
@ NoTunnelEncap
Definition: bgp_path.h:26
ExtCommunityDB * extcomm_db()
Definition: bgp_server.h:194
boost::asio::io_context * ioservice()
Definition: bgp_server.cc:691
void UnregisterAdminDownCallback(int listener)
Definition: bgp_server.cc:836
RoutingInstanceMgr * routing_instance_mgr()
Definition: bgp_server.h:107
bool HasSelfConfiguration() const
Definition: bgp_server.cc:577
int RegisterIdentifierUpdateCallback(IdentifierUpdateCb callback)
Definition: bgp_server.cc:956
uint32_t bgp_identifier() const
Definition: bgp_server.h:216
BgpConfigManager * config_manager()
Definition: bgp_server.h:105
void UnregisterASNUpdateCallback(int listener)
Definition: bgp_server.cc:882
int RegisterAdminDownCallback(AdminDownCb callback)
Definition: bgp_server.cc:820
void UnregisterDSCPUpdateCallback(int listener)
Definition: bgp_server.cc:927
DB * database()
Definition: bgp_server.h:208
as_t autonomous_system() const
Definition: bgp_server.h:213
BgpUpdateSender * update_sender()
Definition: bgp_server.h:103
int RegisterDSCPUpdateCallback(DSCPUpdateCb cb)
Definition: bgp_server.cc:911
BgpAttrDB * attr_db()
Definition: bgp_server.h:188
int RegisterASNUpdateCallback(ASNUpdateCb callback)
Definition: bgp_server.cc:866
BgpMembershipManager * membership_mgr()
Definition: bgp_server.h:180
BgpGlobalSystemConfig * global_config()
Definition: bgp_server.h:298
bool IsReadyForDeletion()
Definition: bgp_server.cc:433
bool admin_down() const
Definition: bgp_server.h:210
bool DeletePath(DBTablePartBase *root, BgpRoute *rt, BgpPath *path)
Definition: bgp_table.cc:835
void LocatePathResolver()
Definition: bgp_table.cc:1084
virtual bool IsVpnTable() const
Definition: bgp_table.h:110
RoutingInstance * routing_instance()
Definition: bgp_table.h:148
virtual Address::Family family() const =0
bool IsDeleted() const
Definition: bgp_table.h:143
void PeerSendReady(IPeerUpdate *peer)
void IdentifierUpdateCallback(Ip4Address old_identifier)
virtual void XmppHandleChannelEvent(XmppChannel *channel, xmps::PeerState state)
virtual bool DeleteChannel(BgpXmppChannel *channel)
void SetQueueDisable(bool disabled)
std::atomic< int32_t > deleting_count_
void VisitChannels(BgpXmppChannelManager::VisitorFn)
uint32_t NumUpPeer() const
void RemoveChannel(XmppChannel *channel)
std::atomic< uint64_t > subscription_gen_id_
void FillPeerInfo(const BgpXmppChannel *channel) const
int32_t deleting_count() const
void ASNUpdateCallback(as_t old_asn, as_t old_local_asn)
BgpXmppChannel * FindChannel(const XmppChannel *channel)
void DSCPUpdateCallback(uint8_t value)
XmppServer * xmpp_server()
WorkQueue< BgpXmppChannel * > queue_
BgpXmppChannelManager(XmppServer *, BgpServer *)
void RoutingInstanceCallback(std::string vrf_name, int op)
XmppChannelMap channel_map_
bool CollectStats(BgpRouterState *state, bool first) const
uint64_t get_subscription_gen_id()
XmppChannelNameMap channel_name_map_
boost::function< void(BgpXmppChannel *)> VisitorFn
uint32_t count() const
virtual BgpXmppChannel * CreateChannel(XmppChannel *channel)
virtual string ToString() const
PeerStats(BgpXmppChannel *peer)
virtual void GetRxRouteUpdateStats(UpdateStats *stats) const
virtual void GetRxErrorStats(RxErrorStats *stats) const
virtual void UpdateTxReachRoute(uint64_t count)
virtual string last_event() const
virtual void GetRxRouteStats(RxRouteStats *stats) const
virtual string last_state() const
virtual string last_error() const
virtual void GetTxProtoStats(ProtoStats *stats) const
virtual void GetTxSocketStats(IPeerDebugStats::SocketStats *stats) const
virtual uint64_t num_flaps() const
virtual void GetRxProtoStats(ProtoStats *stats) const
virtual void UpdateTxUnreachRoute(uint64_t count)
virtual string last_state_change_at() const
virtual void GetRxSocketStats(IPeerDebugStats::SocketStats *stats) const
virtual void GetTxRouteUpdateStats(UpdateStats *stats) const
virtual string last_flap() const
virtual bool IsReady() const
void MembershipRequestCallback(BgpTable *table)
virtual BgpServer * server()
virtual bool SendUpdate(const uint8_t *msg, size_t msgsize)
virtual IPeerClose * peer_close()
virtual const string & ToString() const
virtual bool send_ready() const
virtual const string GetStateName() const
virtual BgpServer * server() const
virtual int GetPrimaryPathCount() const
virtual const IPeerDebugStats * peer_stats() const
virtual const string & ToUVEKey() const
virtual BgpProto::BgpPeerType PeerType() const
virtual bool IsRegistrationRequired() const
virtual void ProcessPathTunnelEncapsulation(const BgpPath *path, BgpAttr *attr, ExtCommunityDB *extcomm_db, const BgpTable *table) const
virtual void UpdatePrimaryPathCount(int count, Address::Family family) const
virtual IPeerDebugStats * peer_stats()
std::atomic< int > total_path_count_
void SetPeerClosed(bool closed)
virtual const std::vector< std::string > GetDefaultTunnelEncap(Address::Family family) const
virtual void UpdateTotalPathCount(int count) const
virtual IPeerClose * peer_close() const
void UpdateCloseRouteStats(Address::Family family, const BgpPath *old_path, uint32_t path_flags) const
virtual bool CanUseMembershipManager() const
virtual bool SendUpdate(const uint8_t *msg, size_t msgsize, const std::string *msg_str)
void WriteReadyCb(const boost::system::error_code &ec)
virtual uint32_t bgp_identifier() const
const bool IsDeleted() const
virtual bool IsAs4Supported() const
virtual void Close(bool graceful)
XmppPeer(BgpServer *server, BgpXmppChannel *channel)
virtual int GetTotalPathCount() const
virtual bool IsXmppPeer() const
virtual bool MembershipPathCallback(DBTablePartBase *tpart, BgpRoute *rt, BgpPath *path)
std::atomic< int > primary_path_count_
virtual bool IsInGRTimerWaitState() const
boost::scoped_ptr< BgpXmppPeerClose > peer_close_
RibExportPolicy bgp_policy_
Timer * eor_receive_timer_
void RoutingInstanceCallback(std::string vrf_name, int op)
virtual ~BgpXmppChannel()
bool ProcessInet6Item(std::string vrf_name, const pugi::xml_node &node, bool add_change)
BgpXmppChannel(XmppChannel *channel, BgpServer *bgp_server=NULL, BgpXmppChannelManager *manager=NULL)
void FillCloseInfo(BgpNeighborResp *resp) const
void set_deleted(bool deleted)
void XMPPPeerInfoSend(const XmppPeerInfoData &peer_info) const
size_t GetMembershipRequestQueueSize() const
void ClearStaledSubscription(RoutingInstance *rt_instance, SubscriptionState *sub_state)
virtual time_t GetEndOfRibSendTime() const
boost::scoped_ptr< BgpXmppRTargetManager > rtarget_manager_
void AddTableMembershipState(const std::string &table_name, TableMembershipRequestState tmr_state)
SubscribedRoutingInstanceList routing_instances_
TcpSession::Endpoint local_endpoint() const
TableMembershipRequestMap table_membership_request_map_
bool ProcessMvpnItem(std::string vrf_name, const pugi::xml_node &item, bool add_change)
virtual TcpSession::Endpoint endpoint() const
void UnregisterTable(int line, BgpTable *table)
PeerCloseManager * close_manager()
bool IsSubscriptionLlgrStale(RoutingInstance *instance) const
BgpXmppChannelManager * manager_
TableMembershipRequestState * GetTableMembershipState(const std::string &table_name)
void CreateType7MvpnRouteRequest(IpAddress grp_address, IpAddress src_address, bool add_change, uint64_t subscription_gen_id, DBRequest &req)
void AddSubscriptionState(RoutingInstance *rt_instance, int index)
virtual bool GetMembershipInfo(BgpTable *table, int *instance_id, uint64_t *subscribed_at, RequestType *req_type)
std::string transport_address_string() const
const XmppSession * GetSession() const
InstanceMembershipRequestMap instance_membership_request_map_
time_t eor_receive_timer_start_time_
void LlgrStaleCurrentSubscriptions()
BgpServer * bgp_server()
WorkQueue< std::string > membership_response_worker_
const std::string & ToUVEKey() const
void set_peer_closed(bool flag)
void DeleteSubscriptionState(RoutingInstance *rt_instance)
uint64_t peer_closed_at() const
void AddInstanceMembershipState(const std::string &instance, InstanceMembershipRequestState imr_state)
bool ProcessItem(std::string vrf_name, const pugi::xml_node &node, bool add_change, int primary_instance_id=0)
void RegisterTable(int line, BgpTable *table, const TableMembershipRequestState *tmr_state)
bool IsSubscriptionGrStale(RoutingInstance *instance) const
ErrorStats & error_stats()
BgpServer * bgp_server_
void MembershipRequestCallback(BgpTable *table)
const std::string & ToString() const
bool IsSubscriptionEmpty() const
void ProcessDeferredSubscribeRequest(RoutingInstance *rt_instance, const InstanceMembershipRequestState &imr_state)
time_t eor_send_timer_start_time_
virtual const InstanceMembershipRequestState * GetInstanceMembershipState(const std::string &instance) const
const BgpXmppChannelManager * manager() const
xmps::PeerId peer_id_
int GetPrimaryInstanceID(const std::string &s, bool expect_prefix_len) const
bool DeleteInstanceMembershipState(const std::string &instance)
std::pair< const std::string, const std::string > VrfTableName
bool EndOfRibReceiveTimerExpired()
TcpSession::Endpoint remote_endpoint() const
void StartEndOfRibReceiveTimer()
void SweepCurrentSubscriptions()
virtual void ReceiveUpdate(const XmppStanza::XmppMessage *msg)
size_t table_membership_requests() const
XmppChannel * channel_
void CreateType5MvpnRouteRequest(IpAddress grp_address, IpAddress src_address, bool add_change, uint64_t subscription_gen_id, int instance_id, DBRequest &req, const autogen::MvpnNextHopType &nh)
void ProcessPendingSubscriptions()
boost::scoped_ptr< PeerStats > peer_stats_
const RoutingInstance::RouteTargetList & GetSubscribedRTargets(RoutingInstance *instance) const
static const int kEndOfRibSendRetryTime
void FlushDeferQ(std::string vrf_name)
void ProcessSubscriptionRequest(std::string rt_instance, const XmppStanza::XmppMessageIq *iq, bool add_change)
void FillTableMembershipInfo(BgpNeighborResp *resp) const
ChannelStats channel_stats_
void EndOfRibTimerErrorHandler(std::string error_name, std::string error_message)
void ReceiveEndOfRIB(Address::Family family)
bool VerifyMembership(const std::string &vrf_name, Address::Family family, BgpTable **table, int *instance_id, uint64_t *subscribed_at, bool *subscribe_pending, bool add_change)
boost::scoped_ptr< PeerCloseManager > close_manager_
bool EndOfRibSendTimerExpired()
void FillInstanceMembershipInfo(BgpNeighborResp *resp) const
bool peer_deleted() const
bool ProcessEnetItem(std::string vrf_name, const pugi::xml_node &item, bool add_change)
bool ProcessMcastItem(std::string vrf_name, const pugi::xml_node &item, bool add_change)
const XmppChannel * channel() const
SubscriptionState * GetSubscriptionState(RoutingInstance *rt_instance)
std::string StateName() const
void StaleCurrentSubscriptions()
bool XmppDecodeAddress(int af, const std::string &address, IpAddress *addrp, bool zero_ok=false)
LabelBlockManagerPtr lb_mgr_
bool ProcessMembershipResponse(std::string table_name, TableMembershipRequestState *tmr_state)
bool MembershipResponseHandler(std::string table_name)
boost::scoped_ptr< XmppPeer > peer_
bool DeleteTableMembershipState(const std::string &table_name)
void DequeueRequest(const std::string &table_name, DBRequest *request)
static uint32_t CommunityFromString(const std::string &comm, boost::system::error_code *perr=NULL)
bool Enqueue(DBRequest *req)
Definition: db_table.cc:221
const std::string & name() const
Definition: db_table.h:111
DBTableBase * parent()
DBTableBase * FindTable(const std::string &name)
Definition: db.cc:68
Definition: etree.h:17
const uint64_t GetExtCommunityValue() const
Definition: etree.h:32
std::string ToString() const
std::string ToXmppIdString() const
static const int32_t kMaxVniSigned
std::vector< uint64_t > communities
Definition: community.h:146
virtual void UpdateRouteStats(Address::Family family, const BgpPath *old_path, uint32_t path_flags) const =0
Definition: ipeer.h:187
virtual const std::string & ToUVEKey() const =0
virtual int GetTotalPathCount() const =0
virtual int GetPrimaryPathCount() const =0
virtual IPeerDebugStats * peer_stats()=0
static Inet6Prefix FromString(const std::string &str, boost::system::error_code *errorp=NULL)
Definition: inet6_route.cc:59
std::string ToString() const
Definition: inet6_route.cc:37
Ip6Address ip6_addr() const
Definition: inet6_route.h:28
int prefixlen() const
Definition: inet6_route.h:34
Ip6Address addr() const
Definition: inet6_route.h:27
int prefixlen() const
Definition: inet_route.h:28
Ip4Address ip4_addr() const
Definition: inet_route.h:26
std::string ToString() const
Definition: inet_route.cc:61
static Ip4Prefix FromString(const std::string &str, boost::system::error_code *errorp=NULL)
Definition: inet_route.cc:85
This class encapsulates the wire-format representation of a BGP Large Community attribute and provide...
Definition: community.h:509
std::vector< uint32_t > communities
Vector of community values. Each Large Community value consists of three 4-byte fields (12 bytes tota...
Definition: community.h:541
const bool IsDefault() const
const uint64_t GetExtCommunityValue() const
Definition: load_balance.h:121
const uint64_t GetExtCommunityValue() const
bool IsBroadcast() const
Definition: mac_address.cc:34
bool IsZero() const
Definition: mac_address.cc:30
static MacAddress FromString(const std::string &str, boost::system::error_code *error=NULL)
Definition: mac_address.cc:72
const uint64_t GetExtCommunityValue() const
Definition: mac_mobility.h:32
@ SourceTreeJoinRoute
Definition: mvpn_route.h:47
@ SourceActiveADRoute
Definition: mvpn_route.h:45
bool IsCloseInProgress() const
bool IsInGRTimerWaitState() const
static void FillPeerUpdateStats(const IPeerDebugStats *peer_stats, PeerStatsData *peer_stats_data)
Definition: peer_stats.cc:55
static void FillPeerDebugStats(const IPeerDebugStats *peer_stats, PeerStatsInfo *stats)
Definition: peer_stats.cc:65
static RouteDistinguisher kZeroRd
Definition: rd.h:15
const uint64_t GetExtCommunityValue() const
Definition: router_mac.h:30
RoutingInstance * GetRoutingInstance(const std::string &name)
void UnregisterInstanceOpCallback(int id)
int RegisterInstanceOpCallback(RoutingInstanceCb cb)
const std::string & name() const
bool deleted() const
static std::string GetTableName(std::string instance_name, Address::Family fmly)
std::map< std::string, BgpTable * > RouteTableList
RouteTableList & GetTables()
const RouteTargetList & GetImportList() const
std::set< RouteTarget > RouteTargetList
BgpTable * GetTable(Address::Family fmly)
static SandeshLevel::type LoggingUtLevel()
Definition: cpp/sandesh.h:225
const uint64_t GetExtCommunityValue() const
const uint64_t GetExtCommunityValue() const
Represents a single BGP Large Community tag.
const std::vector< uint32_t > GetLargeCommunityValue() const
Returns the community value as a vector of 3 32-bit integers.
The TaskScheduler keeps track of what tasks are currently schedulable. When a task is enqueued it is ...
Definition: task.h:307
int GetTaskId(const std::string &name)
Definition: task.cc:884
static TaskScheduler * GetInstance()
Definition: task.cc:574
const io::SocketStats & GetSocketStats() const
Definition: tcp_session.h:159
boost::asio::ip::tcp::endpoint Endpoint
Definition: tcp_session.h:59
Endpoint remote_endpoint() const
Definition: tcp_session.h:132
Endpoint local_endpoint() const
Definition: tcp_session.cc:207
static bool DeleteTimer(Timer *Timer)
Definition: timer.cc:222
static Timer * CreateTimer(boost::asio::io_context &service, const std::string &name, int task_id=Timer::GetTimerTaskId(), int task_instance=Timer::GetTimerInstanceId(), bool delete_on_completion=false)
Definition: timer.cc:201
Definition: timer.h:58
bool Cancel()
Definition: timer.cc:150
bool running() const
Definition: timer.h:90
bool Start(int time, Handler handler, ErrorHandler error_handler=NULL)
Definition: timer.cc:108
bool Reschedule(int time)
Definition: timer.cc:137
const uint64_t GetExtCommunityValue() const
Definition: tunnel_encap.h:33
TunnelEncapType::Encap tunnel_encap() const
Definition: tunnel_encap.cc:41
bool Enqueue(QueueEntryT entry)
Definition: queue_task.h:249
void set_disable(bool disabled)
Definition: queue_task.h:320
size_t Length() const
Definition: queue_task.h:357
void Shutdown(bool delete_entries=true)
Definition: queue_task.h:153
void SetEntryCallback(TaskEntryCallback on_entry)
Definition: queue_task.h:300
virtual void RegisterReceive(xmps::PeerId, ReceiveCb)=0
virtual std::string LastEvent() const =0
virtual void UnRegisterReceive(xmps::PeerId)=0
virtual const XmppConnection * connection() const =0
virtual uint32_t tx_close() const =0
virtual void RegisterReferer(xmps::PeerId)
Definition: xmpp_channel.h:64
virtual const std::string & ToString() const =0
virtual xmps::PeerState GetPeerState() const =0
virtual std::string LastFlap() const =0
virtual void Close()=0
virtual bool LastSent(time_t duration) const =0
virtual uint32_t tx_open() const =0
virtual uint32_t rx_update() const =0
virtual uint32_t rx_close() const =0
virtual void UnRegisterReferer(xmps::PeerId)
Definition: xmpp_channel.h:65
virtual uint32_t tx_update() const =0
virtual uint32_t tx_keepalive() const =0
virtual std::string LastStateName() const =0
virtual bool LastReceived(time_t duration) const =0
virtual std::string LastStateChangeAt() const =0
virtual uint32_t rx_keepalive() const =0
virtual uint32_t FlapCount() const =0
virtual void UnRegisterWriteReady(xmps::PeerId id)=0
virtual uint32_t rx_open() const =0
virtual int GetTaskInstance() const =0
virtual bool Send(const uint8_t *, size_t, xmps::PeerId, SendReadyCb)=0
virtual std::string StateName() const =0
bool Send(const uint8_t *data, size_t size, const std::string *msg_str=NULL)
const XmppSession * session() const
bool IsActiveChannel() const
bool IsDeleted() const
virtual boost::asio::ip::tcp::endpoint endpoint() const
const std::string & ToUVEKey() const
static const char * kControlNodeJID
Definition: xmpp_init.h:18
static const char * kBgpPeer
Definition: xmpp_init.h:25
static const char * kEndOfRibMarker
Definition: xmpp_init.h:27
void ClearAllConnections()
Definition: xmpp_server.cc:446
void SetDscpValue(uint8_t value)
Definition: xmpp_server.cc:586
void UnRegisterConnectionEvent(xmps::PeerId)
Definition: xmpp_server.cc:458
void CreateConfigUpdater(BgpConfigManager *config_manager)
Definition: xmpp_server.cc:235
void RegisterConnectionEvent(xmps::PeerId, ConnectionEventCb)
Definition: xmpp_server.cc:453
uint32_t GetEndOfRibSendTime() const
Definition: xmpp_server.cc:259
uint32_t GetEndOfRibReceiveTime() const
Definition: xmpp_server.cc:253
XmppMessageType type
Definition: xmpp_proto.h:58
std::unique_ptr< XmlBase > dom
Definition: xmpp_proto.h:63
Event
Definition: http_client.h:30
boost::intrusive_ptr< LabelBlock > LabelBlockPtr
Definition: label_block.h:20
static bool regex_search(const std::string &input, const regex &regex)
Definition: regex.h:26
static bool regex_match(const std::string &input, const regex &regex)
Definition: regex.h:35
@ READY
Definition: xmpp_channel.h:18
@ TIMEDOUT
Definition: xmpp_channel.h:20
@ UNKNOWN
Definition: xmpp_channel.h:17
@ NOT_READY
Definition: xmpp_channel.h:19
static bool stringToIntegerList(std::string input, std::string seperator, std::vector< NumberType > &entries)
Definition: string_util.h:108
uint32_t local_pref
Definition: bgp_attr.h:116
std::atomic< uint64_t > table_unsubscribe_complete
std::atomic< uint64_t > instance_subscribe
std::atomic< uint64_t > table_subscribe
std::atomic< uint64_t > instance_unsubscribe
std::atomic< uint64_t > table_subscribe_complete
std::atomic< uint64_t > table_unsubscribe
uint64_t get_inet6_rx_bad_xml_token_count() const
uint64_t get_inet6_rx_bad_nexthop_count() const
uint64_t get_inet6_rx_bad_afi_safi_count() const
std::atomic< uint64_t > inet6_rx_bad_xml_token_count
uint64_t get_inet6_rx_bad_prefix_count() const
std::atomic< uint64_t > reach
std::atomic< uint64_t > end_of_rib
std::atomic< uint64_t > rt_updates
std::atomic< uint64_t > unreach
RoutingInstance::RouteTargetList targets
std::vector< uint32_t > communities
Definition: community.h:36
DBOperation oper
Definition: db_table.h:43
@ DB_ENTRY_DELETE
Definition: db_table.h:40
@ DB_ENTRY_ADD_CHANGE
Definition: db_table.h:39
std::unique_ptr< DBRequestKey > key
Definition: db_table.h:49
void Swap(DBRequest *rhs)
Definition: db_table.cc:46
std::unique_ptr< DBRequestData > data
Definition: db_table.h:50
uint64_t inet6_bad_afi_safi_count
Definition: ipeer.h:86
uint64_t inet6_bad_prefix_count
Definition: ipeer.h:84
uint64_t inet6_bad_xml_token_count
Definition: ipeer.h:83
uint64_t inet6_bad_nexthop_count
Definition: ipeer.h:85
uint64_t blocked_duration_usecs
Definition: ipeer.h:121
uint8_t tunnel_flags
Definition: bgp_attr.h:359
@ EdgeReplicationSupported
Definition: bgp_attr.h:319
@ IngressReplication
Definition: bgp_attr.h:335
@ AssistedReplicationContrail
Definition: bgp_attr.h:337
uint8_t tunnel_type
Definition: bgp_attr.h:360
void SetIdentifier(Ip4Address identifier)
Definition: bgp_attr.cc:341
void SetLabel(uint32_t label, const ExtCommunity *ext)
Definition: bgp_attr.cc:329
std::atomic< uint64_t > write_calls
Definition: io_utils.h:24
std::atomic< uint64_t > write_blocked_duration_usecs
Definition: io_utils.h:29
std::atomic< uint64_t > read_bytes
Definition: io_utils.h:22
std::atomic< uint64_t > write_blocked
Definition: io_utils.h:28
std::atomic< uint64_t > read_calls
Definition: io_utils.h:21
std::atomic< uint64_t > write_bytes
Definition: io_utils.h:25
#define CHECK_CONCURRENCY(...)
static time_t UTCTimestamp()
Definition: time_util.h:24
static uint64_t UTCTimestampUsec()
Definition: time_util.h:14
void STLDeleteElements(Container *container)
Definition: util.h:115