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