/
bgp_xmpp_channel.cc
2529 lines (2228 loc) · 89.6 KB
/
bgp_xmpp_channel.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "bgp/bgp_xmpp_channel.h"
#include <boost/foreach.hpp>
#include <limits>
#include <vector>
#include <sstream>
#include "base/task_annotations.h"
#include "bgp/bgp_config.h"
#include "bgp/bgp_factory.h"
#include "bgp/bgp_log.h"
#include "bgp/bgp_peer_close.h"
#include "bgp/bgp_peer_membership.h"
#include "bgp/inet/inet_table.h"
#include "bgp/inet6/inet6_table.h"
#include "bgp/extended-community/load_balance.h"
#include "bgp/extended-community/mac_mobility.h"
#include "bgp/ermvpn/ermvpn_table.h"
#include "bgp/evpn/evpn_table.h"
#include "bgp/rtarget/rtarget_table.h"
#include "bgp/scheduling_group.h"
#include "bgp/security_group/security_group.h"
#include "bgp/tunnel_encap/tunnel_encap.h"
#include "net/community_type.h"
#include "schema/xmpp_multicast_types.h"
#include "schema/xmpp_enet_types.h"
#include "xml/xml_pugi.h"
#include "xmpp/xmpp_connection.h"
#include "xmpp/xmpp_server.h"
#include "xmpp/sandesh/xmpp_peer_info_types.h"
using autogen::EnetItemType;
using autogen::EnetNextHopListType;
using autogen::EnetSecurityGroupListType;
using autogen::EnetTunnelEncapsulationListType;
using autogen::McastItemType;
using autogen::McastNextHopsType;
using autogen::McastTunnelEncapsulationListType;
using autogen::ItemType;
using autogen::NextHopListType;
using autogen::SecurityGroupListType;
using autogen::CommunityTagListType;
using autogen::TunnelEncapsulationListType;
using boost::system::error_code;
using pugi::xml_node;
using std::auto_ptr;
using std::make_pair;
using std::numeric_limits;
using std::ostringstream;
using std::pair;
using std::set;
using std::string;
using std::vector;
//
// Calculate med from local preference.
// Should move agent definitions to a common location and use those here
// instead of hard coded values.
//
static uint32_t GetMedFromLocalPref(uint32_t local_pref) {
if (local_pref == 0)
return 0;
if (local_pref == 100)
return 200;
if (local_pref == 200)
return 100;
return numeric_limits<uint32_t>::max() - local_pref;
}
BgpXmppChannel::ErrorStats::ErrorStats()
: inet6_rx_bad_xml_token_count(0), inet6_rx_bad_prefix_count(0),
inet6_rx_bad_nexthop_count(0), inet6_rx_bad_afi_safi_count(0) {
}
void BgpXmppChannel::ErrorStats::incr_inet6_rx_bad_xml_token_count() {
++inet6_rx_bad_xml_token_count;
}
void BgpXmppChannel::ErrorStats::incr_inet6_rx_bad_prefix_count() {
++inet6_rx_bad_prefix_count;
}
void BgpXmppChannel::ErrorStats::incr_inet6_rx_bad_nexthop_count() {
++inet6_rx_bad_nexthop_count;
}
void BgpXmppChannel::ErrorStats::incr_inet6_rx_bad_afi_safi_count() {
++inet6_rx_bad_afi_safi_count;
}
uint64_t BgpXmppChannel::ErrorStats::get_inet6_rx_bad_xml_token_count() const {
return inet6_rx_bad_xml_token_count;
}
uint64_t BgpXmppChannel::ErrorStats::get_inet6_rx_bad_prefix_count() const {
return inet6_rx_bad_prefix_count;
}
uint64_t BgpXmppChannel::ErrorStats::get_inet6_rx_bad_nexthop_count() const {
return inet6_rx_bad_nexthop_count;
}
uint64_t BgpXmppChannel::ErrorStats::get_inet6_rx_bad_afi_safi_count() const {
return inet6_rx_bad_afi_safi_count;
}
BgpXmppChannel::Stats::Stats()
: rt_updates(0), reach(0), unreach(0) {
}
BgpXmppChannel::ChannelStats::ChannelStats()
: instance_subscribe(0),
instance_unsubscribe(0),
table_subscribe(0),
table_subscribe_complete(0),
table_unsubscribe(0),
table_unsubscribe_complete(0) {
}
class BgpXmppChannel::PeerClose : public IPeerClose {
public:
explicit PeerClose(BgpXmppChannel *channel)
: parent_(channel),
manager_(BgpObjectFactory::Create<PeerCloseManager>(channel->Peer())) {
}
virtual ~PeerClose() {
}
virtual string ToString() const {
return parent_ ? parent_->ToString() : "";
}
virtual PeerCloseManager *close_manager() {
return manager_.get();
}
virtual bool IsCloseGraceful() {
if (!parent_ || !parent_->channel_) return false;
XmppConnection *connection =
const_cast<XmppConnection *>(parent_->channel_->connection());
if (!connection || connection->IsActiveChannel()) return false;
// Check from the server, if GR is enabled or not.
return static_cast<XmppServer *>(
connection->server())->IsPeerCloseGraceful();
}
virtual void CustomClose() {
if (parent_->rtarget_routes_.empty()) return;
BgpServer *server = parent_->bgp_server_;
RoutingInstanceMgr *instance_mgr = server->routing_instance_mgr();
RoutingInstance *master =
instance_mgr->GetRoutingInstance(BgpConfigManager::kMasterInstance);
assert(master);
BgpTable *rtarget_table = master->GetTable(Address::RTARGET);
assert(rtarget_table);
for (PublishedRTargetRoutes::iterator
it = parent_->rtarget_routes_.begin();
it != parent_->rtarget_routes_.end(); it++) {
parent_->RTargetRouteOp(rtarget_table,
server->local_autonomous_system(),
it->first, NULL, false);
}
parent_->routing_instances_.clear();
parent_->rtarget_routes_.clear();
}
virtual bool CloseComplete(bool from_timer, bool gr_cancelled) {
if (!parent_) return true;
if (!from_timer) {
// If graceful restart is enabled, do not delete this peer yet
// However, if a gr is already aborted, do not trigger another gr
if (!gr_cancelled && IsCloseGraceful()) {
return false;
}
} else {
// Close is complete off graceful restart timer. Delete this peer
// if the session has not come back up
if (parent_->Peer()->IsReady()) return false;
}
XmppConnection *connection =
const_cast<XmppConnection *>(parent_->channel_->connection());
// TODO(ananth): This needs to be cleaned up properly by clearly
// separating GR entry and exit steps. Avoid duplicate channel
// deletions.
if (connection && !connection->IsActiveChannel()) {
parent_->manager_->Enqueue(parent_);
parent_ = NULL;
}
return true;
}
void Close() {
manager_->Close();
}
private:
BgpXmppChannel *parent_;
auto_ptr<PeerCloseManager> manager_;
};
class BgpXmppChannel::PeerStats : public IPeerDebugStats {
public:
explicit PeerStats(BgpXmppChannel *peer)
: peer_(peer) {
}
// Used when peer flaps.
// Don't need to do anything since the BgpXmppChannel itself gets deleted.
virtual void Clear() {
}
// Printable name
virtual string ToString() const {
return peer_->ToString();
}
// Previous State of the peer
virtual string last_state() const {
return (peer_->channel_->LastStateName());
}
// Last state change occurred at
virtual string last_state_change_at() const {
return (peer_->channel_->LastStateChangeAt());
}
// Last error on this peer
virtual string last_error() const {
return "";
}
// Last Event on this peer
virtual string last_event() const {
return (peer_->channel_->LastEvent());
}
// When was the Last
virtual string last_flap() const {
return (peer_->channel_->LastFlap());
}
// Total number of flaps
virtual uint64_t num_flaps() const {
return (peer_->channel_->FlapCount());
}
virtual void GetRxProtoStats(ProtoStats *stats) const {
stats->open = peer_->channel_->rx_open();
stats->close = peer_->channel_->rx_close();
stats->keepalive = peer_->channel_->rx_keepalive();
stats->update = peer_->channel_->rx_update();
}
virtual void GetTxProtoStats(ProtoStats *stats) const {
stats->open = peer_->channel_->tx_open();
stats->close = peer_->channel_->tx_close();
stats->keepalive = peer_->channel_->tx_keepalive();
stats->update = peer_->channel_->tx_update();
}
virtual void GetRxRouteUpdateStats(UpdateStats *stats) const {
stats->total = peer_->stats_[RX].rt_updates;
stats->reach = peer_->stats_[RX].reach;
stats->unreach = peer_->stats_[RX].unreach;
}
virtual void GetTxRouteUpdateStats(UpdateStats *stats) const {
stats->total = peer_->stats_[TX].rt_updates;
stats->reach = peer_->stats_[TX].reach;
stats->unreach = peer_->stats_[TX].unreach;
}
virtual void GetRxSocketStats(IPeerDebugStats::SocketStats *stats) const {
const XmppSession *session = peer_->GetSession();
if (session) {
io::SocketStats socket_stats(session->GetSocketStats());
stats->calls = socket_stats.read_calls;
stats->bytes = socket_stats.read_bytes;
}
}
virtual void GetTxSocketStats(IPeerDebugStats::SocketStats *stats) const {
const XmppSession *session = peer_->GetSession();
if (session) {
io::SocketStats socket_stats(session->GetSocketStats());
stats->calls = socket_stats.write_calls;
stats->bytes = socket_stats.write_bytes;
stats->blocked_count = socket_stats.write_blocked;
stats->blocked_duration_usecs =
socket_stats.write_blocked_duration_usecs;
}
}
virtual void GetRxErrorStats(RxErrorStats *stats) const {
const BgpXmppChannel::ErrorStats &err_stats = peer_->error_stats();
stats->inet6_bad_xml_token_count =
err_stats.get_inet6_rx_bad_xml_token_count();
stats->inet6_bad_prefix_count =
err_stats.get_inet6_rx_bad_prefix_count();
stats->inet6_bad_nexthop_count =
err_stats.get_inet6_rx_bad_nexthop_count();
stats->inet6_bad_afi_safi_count =
err_stats.get_inet6_rx_bad_afi_safi_count();
}
virtual void UpdateTxUnreachRoute(uint64_t count) {
peer_->stats_[TX].unreach += count;
}
virtual void UpdateTxReachRoute(uint64_t count) {
peer_->stats_[TX].reach += count;
}
private:
BgpXmppChannel *peer_;
};
class BgpXmppChannel::XmppPeer : public IPeer {
public:
XmppPeer(BgpServer *server, BgpXmppChannel *channel)
: server_(server),
parent_(channel),
is_deleted_(false),
send_ready_(true),
deleted_at_(0) {
refcount_ = 0;
primary_path_count_ = 0;
}
virtual ~XmppPeer() {
assert(GetRefCount() == 0);
}
virtual bool SendUpdate(const uint8_t *msg, size_t msgsize);
virtual string ToString() const {
return parent_->ToString();
}
virtual string ToUVEKey() const {
return parent_->ToUVEKey();
}
virtual BgpServer *server() {
return server_;
}
virtual IPeerClose *peer_close() {
return parent_->peer_close_.get();
}
virtual IPeerDebugStats *peer_stats() {
return parent_->peer_stats_.get();
}
virtual const IPeerDebugStats *peer_stats() const {
return parent_->peer_stats_.get();
}
virtual bool IsReady() const {
return (parent_->channel_->GetPeerState() == xmps::READY);
}
virtual const string GetStateName() const {
switch (parent_->channel_->GetPeerState()) {
case xmps::UNKNOWN: return "UNKNOWN";
case xmps::READY: return "READY";
case xmps::NOT_READY: return "NOT_READY";
case xmps::TIMEDOUT: return "TIMEDOUT";
}
return "UNKNOWN";
}
virtual bool IsXmppPeer() const {
return true;
}
virtual void Close();
const bool IsDeleted() const { return is_deleted_; }
void SetDeleted(bool deleted) {
is_deleted_ = deleted;
if (is_deleted_)
deleted_at_ = UTCTimestampUsec();
}
uint64_t deleted_at() const { return deleted_at_; }
virtual BgpProto::BgpPeerType PeerType() const {
return BgpProto::XMPP;
}
virtual uint32_t bgp_identifier() const {
const TcpSession::Endpoint &remote = parent_->endpoint();
if (remote.address().is_v4()) {
return remote.address().to_v4().to_ulong();
}
return 0;
}
virtual void UpdateRefCount(int count) const { refcount_ += count; }
virtual tbb::atomic<int> GetRefCount() const { return refcount_; }
virtual void UpdatePrimaryPathCount(int count) const {
primary_path_count_ += count;
}
virtual int GetPrimaryPathCount() const {
return primary_path_count_;
}
private:
void WriteReadyCb(const boost::system::error_code &ec) {
if (!server_) return;
SchedulingGroupManager *sg_mgr = server_->scheduling_group_manager();
BGP_LOG_PEER(Event, this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_ALL,
BGP_PEER_DIR_NA, "Send ready");
sg_mgr->SendReady(this);
send_ready_ = true;
XmppPeerInfoData peer_info;
peer_info.set_name(ToUVEKey());
peer_info.set_send_state("in sync");
XMPPPeerInfo::Send(peer_info);
}
BgpServer *server_;
BgpXmppChannel *parent_;
mutable tbb::atomic<int> refcount_;
mutable tbb::atomic<int> primary_path_count_;
bool is_deleted_;
bool send_ready_;
uint64_t deleted_at_;
};
static bool SkipUpdateSend() {
static bool init_;
static bool skip_;
if (init_) return skip_;
skip_ = getenv("XMPP_SKIP_UPDATE_SEND") != NULL;
init_ = true;
return skip_;
}
bool BgpXmppChannel::XmppPeer::SendUpdate(const uint8_t *msg, size_t msgsize) {
XmppChannel *channel = parent_->channel_;
if (channel->GetPeerState() == xmps::READY) {
parent_->stats_[TX].rt_updates++;
if (SkipUpdateSend()) return true;
send_ready_ = channel->Send(msg, msgsize, xmps::BGP,
boost::bind(&BgpXmppChannel::XmppPeer::WriteReadyCb, this, _1));
if (!send_ready_) {
BGP_LOG_PEER(Event, this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_ALL,
BGP_PEER_DIR_NA, "Send blocked");
XmppPeerInfoData peer_info;
peer_info.set_name(ToUVEKey());
peer_info.set_send_state("not in sync");
XMPPPeerInfo::Send(peer_info);
}
return send_ready_;
} else {
return false;
}
}
void BgpXmppChannel::XmppPeer::Close() {
SetDeleted(true);
if (server_ == NULL) {
return;
}
parent_->peer_close_->Close();
}
BgpXmppChannel::BgpXmppChannel(XmppChannel *channel, BgpServer *bgp_server,
BgpXmppChannelManager *manager)
: channel_(channel),
peer_id_(xmps::BGP),
bgp_server_(bgp_server),
peer_(new XmppPeer(bgp_server, this)),
peer_close_(new PeerClose(this)),
peer_stats_(new PeerStats(this)),
bgp_policy_(peer_->PeerType(), RibExportPolicy::XMPP, 0, -1, 0),
manager_(manager),
close_in_progress_(false),
deleted_(false),
defer_peer_close_(false),
membership_response_worker_(
TaskScheduler::GetInstance()->GetTaskId("xmpp::StateMachine"),
channel->connection()->GetIndex(),
boost::bind(&BgpXmppChannel::MembershipResponseHandler, this, _1)),
lb_mgr_(new LabelBlockManager()) {
channel_->RegisterReceive(peer_id_,
boost::bind(&BgpXmppChannel::ReceiveUpdate, this, _1));
BGP_LOG_PEER(Event, peer_.get(), SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
BGP_PEER_DIR_NA, "Created");
}
BgpXmppChannel::~BgpXmppChannel() {
if (channel_->connection() && !channel_->connection()->IsActiveChannel()) {
CHECK_CONCURRENCY("bgp::Config");
}
if (manager_)
manager_->RemoveChannel(channel_);
if (manager_ && close_in_progress_)
manager_->decrement_closing_count();
STLDeleteElements(&defer_q_);
assert(peer_->IsDeleted());
BGP_LOG_PEER(Event, peer_.get(), SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
BGP_PEER_DIR_NA, "Deleted");
channel_->UnRegisterReceive(peer_id_);
}
const XmppSession *BgpXmppChannel::GetSession() const {
if (channel_ && channel_->connection()) {
return channel_->connection()->session();
}
return NULL;
}
string BgpXmppChannel::ToString() const {
return channel_->ToString();
}
string BgpXmppChannel::ToUVEKey() const {
if (channel_->connection()) {
return channel_->connection()->ToUVEKey();
} else {
return channel_->ToString();
}
}
string BgpXmppChannel::StateName() const {
return channel_->StateName();
}
void BgpXmppChannel::RTargetRouteOp(BgpTable *rtarget_table, as4_t asn,
const RouteTarget &rtarget, BgpAttrPtr attr,
bool add_change) {
if (add_change && close_in_progress_)
return;
DBRequest req;
RTargetPrefix rt_prefix(asn, rtarget);
req.key.reset(new RTargetTable::RequestKey(rt_prefix, Peer()));
if (add_change) {
req.data.reset(new RTargetTable::RequestData(attr, 0, 0));
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
} else {
req.oper = DBRequest::DB_ENTRY_DELETE;
}
rtarget_table->Enqueue(&req);
}
void BgpXmppChannel::ASNUpdateCallback(as_t old_asn, as_t old_local_asn) {
if (bgp_server_->local_autonomous_system() == old_local_asn)
return;
if (routing_instances_.empty())
return;
RoutingInstanceMgr *instance_mgr = bgp_server_->routing_instance_mgr();
assert(instance_mgr);
RoutingInstance *master =
instance_mgr->GetRoutingInstance(BgpConfigManager::kMasterInstance);
assert(master);
BgpTable *rtarget_table = master->GetTable(Address::RTARGET);
assert(rtarget_table);
BgpAttrSpec attrs;
BgpAttrNextHop nexthop(bgp_server_->bgp_identifier());
attrs.push_back(&nexthop);
BgpAttrOrigin origin(BgpAttrOrigin::IGP);
attrs.push_back(&origin);
BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attrs);
// Delete the route and add with new local ASN
for (PublishedRTargetRoutes::iterator it = rtarget_routes_.begin();
it != rtarget_routes_.end(); it++) {
RTargetRouteOp(rtarget_table, old_local_asn, it->first, NULL, false);
RTargetRouteOp(rtarget_table, bgp_server_->local_autonomous_system(),
it->first, attr, true);
}
}
void BgpXmppChannel::IdentifierUpdateCallback(Ip4Address old_identifier) {
if (routing_instances_.empty())
return;
RoutingInstanceMgr *instance_mgr = bgp_server_->routing_instance_mgr();
assert(instance_mgr);
RoutingInstance *master =
instance_mgr->GetRoutingInstance(BgpConfigManager::kMasterInstance);
assert(master);
BgpTable *rtarget_table = master->GetTable(Address::RTARGET);
assert(rtarget_table);
BgpAttrSpec attrs;
BgpAttrNextHop nexthop(bgp_server_->bgp_identifier());
attrs.push_back(&nexthop);
BgpAttrOrigin origin(BgpAttrOrigin::IGP);
attrs.push_back(&origin);
BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attrs);
// Update the route with new nexthop
for (PublishedRTargetRoutes::iterator it = rtarget_routes_.begin();
it != rtarget_routes_.end(); it++) {
RTargetRouteOp(rtarget_table, bgp_server_->local_autonomous_system(),
it->first, attr, true);
}
}
void
BgpXmppChannel::AddNewRTargetRoute(BgpTable *rtarget_table,
RoutingInstance *rtinstance,
const RouteTarget &rtarget,
BgpAttrPtr attr) {
PublishedRTargetRoutes::iterator rt_loc = rtarget_routes_.find(rtarget);
if (rt_loc == rtarget_routes_.end()) {
pair<PublishedRTargetRoutes::iterator, bool> ret =
rtarget_routes_.insert(make_pair(rtarget, RoutingInstanceList()));
rt_loc = ret.first;
// Send rtarget route ADD
RTargetRouteOp(rtarget_table,
bgp_server_->local_autonomous_system(),
rtarget, attr, true);
}
rt_loc->second.insert(rtinstance);
}
void
BgpXmppChannel::DeleteRTargetRoute(BgpTable *rtarget_table,
RoutingInstance *rtinstance,
const RouteTarget &rtarget) {
PublishedRTargetRoutes::iterator rt_loc = rtarget_routes_.find(rtarget);
assert(rt_loc != rtarget_routes_.end());
assert(rt_loc->second.erase(rtinstance));
if (rt_loc->second.empty()) {
rtarget_routes_.erase(rtarget);
// Send rtarget route DELETE
RTargetRouteOp(rtarget_table,
bgp_server_->local_autonomous_system(),
rtarget, NULL, false);
}
}
void BgpXmppChannel::RoutingInstanceCallback(string vrf_name, int op) {
if (close_in_progress_)
return;
if (vrf_name == BgpConfigManager::kMasterInstance)
return;
if (op == RoutingInstanceMgr::INSTANCE_DELETE)
return;
RoutingInstanceMgr *instance_mgr = bgp_server_->routing_instance_mgr();
assert(instance_mgr);
RoutingInstance *rt_instance = instance_mgr->GetRoutingInstance(vrf_name);
assert(rt_instance);
if (op == RoutingInstanceMgr::INSTANCE_ADD) {
VrfMembershipRequestMap::iterator it =
vrf_membership_request_map_.find(vrf_name);
if (it == vrf_membership_request_map_.end())
return;
ProcessDeferredSubscribeRequest(rt_instance, it->second);
vrf_membership_request_map_.erase(it);
} else {
SubscribedRoutingInstanceList::iterator it =
routing_instances_.find(rt_instance);
if (it == routing_instances_.end()) return;
// Prepare for route add to rtarget table
// get rtarget_table and locate the attr
RoutingInstance *master =
instance_mgr->GetRoutingInstance(BgpConfigManager::kMasterInstance);
assert(master);
BgpTable *rtarget_table = master->GetTable(Address::RTARGET);
assert(rtarget_table);
BgpAttrSpec attrs;
BgpAttrNextHop nexthop(bgp_server_->bgp_identifier());
attrs.push_back(&nexthop);
BgpAttrOrigin origin(BgpAttrOrigin::IGP);
attrs.push_back(&origin);
BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attrs);
// Import list in the routing instance
const RoutingInstance::RouteTargetList &new_list =
rt_instance->GetImportList();
// Previous route target list for which the rtarget route was added
RoutingInstance::RouteTargetList ¤t = it->second.targets;
RoutingInstance::RouteTargetList::iterator cur_next_it, cur_it;
cur_it = cur_next_it = current.begin();
RoutingInstance::RouteTargetList::const_iterator new_it =
new_list.begin();
pair<RoutingInstance::RouteTargetList::iterator, bool> r;
while (cur_it != current.end() && new_it != new_list.end()) {
if (*new_it < *cur_it) {
r = current.insert(*new_it);
assert(r.second);
AddNewRTargetRoute(rtarget_table, it->first, *new_it, attr);
new_it++;
} else if (*new_it > *cur_it) {
cur_next_it++;
DeleteRTargetRoute(rtarget_table, it->first, *cur_it);
current.erase(cur_it);
cur_it = cur_next_it;
} else {
// Update
cur_it++;
new_it++;
}
cur_next_it = cur_it;
}
for (; new_it != new_list.end(); ++new_it) {
r = current.insert(*new_it);
assert(r.second);
AddNewRTargetRoute(rtarget_table, it->first, *new_it, attr);
}
for (cur_next_it = cur_it;
cur_it != current.end();
cur_it = cur_next_it) {
cur_next_it++;
DeleteRTargetRoute(rtarget_table, it->first, *cur_it);
current.erase(cur_it);
}
}
}
IPeer *BgpXmppChannel::Peer() {
return peer_.get();
}
const IPeer *BgpXmppChannel::Peer() const {
return peer_.get();
}
TcpSession::Endpoint BgpXmppChannel::endpoint() const {
return channel_->connection()->endpoint();
}
bool BgpXmppChannel::XmppDecodeAddress(int af, const string &address,
IpAddress *addrp, bool zero_ok) {
switch (af) {
case BgpAf::IPv4:
break;
default:
return false;
}
error_code error;
*addrp = IpAddress::from_string(address, error);
if (error) {
return false;
}
if (zero_ok) {
return true;
} else {
return (addrp->to_v4().to_ulong() != 0);
}
}
//
// Return true if there's a pending request, false otherwise.
//
bool BgpXmppChannel::GetMembershipInfo(BgpTable *table,
int *instance_id, uint64_t *subscription_gen_id, RequestType *req_type) {
*instance_id = -1;
*subscription_gen_id = 0;
RoutingTableMembershipRequestMap::iterator loc =
routingtable_membership_request_map_.find(table->name());
if (loc != routingtable_membership_request_map_.end()) {
*req_type = loc->second.pending_req;
*instance_id = loc->second.instance_id;
return true;
} else {
*req_type = NONE;
PeerRibMembershipManager *mgr = bgp_server_->membership_mgr();
mgr->GetRegistrationInfo(peer_.get(), table,
instance_id, subscription_gen_id);
return false;
}
}
//
// Return true if there's a pending request, false otherwise.
//
bool BgpXmppChannel::GetMembershipInfo(const string &vrf_name,
int *instance_id) {
*instance_id = -1;
VrfMembershipRequestMap::iterator loc =
vrf_membership_request_map_.find(vrf_name);
if (loc != vrf_membership_request_map_.end()) {
*instance_id = loc->second;
return true;
} else {
return false;
}
}
//
// Verify that there's a subscribe or pending subscribe for the table
// corresponding to the vrf and family.
// If there's a subscribe, populate the table and instance_id.
// If there's a pending subscribe, populate the instance_id.
// The subscribe_pending parameter is set appropriately.
//
// Return true if there's a subscribe or pending subscribe, false otherwise.
//
bool BgpXmppChannel::VerifyMembership(const string &vrf_name,
Address::Family family, BgpTable **table,
int *instance_id, uint64_t *subscription_gen_id, bool *subscribe_pending) {
*table = NULL;
*subscribe_pending = false;
RoutingInstanceMgr *instance_mgr = bgp_server_->routing_instance_mgr();
RoutingInstance *rt_instance = instance_mgr->GetRoutingInstance(vrf_name);
if (rt_instance != NULL && !rt_instance->deleted()) {
*table = rt_instance->GetTable(family);
RequestType req_type;
if (GetMembershipInfo(*table, instance_id,
subscription_gen_id, &req_type)) {
// Bail if there's a pending unsubscribe.
if (req_type != SUBSCRIBE) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Received route after unsubscribe");
return false;
}
*subscribe_pending = true;
} else {
// Bail if we are not subscribed to the table.
if (*instance_id < 0) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Received route without subscribe");
return false;
}
}
} else {
// Bail if there's no pending subscribe.
if (GetMembershipInfo(vrf_name, instance_id)) {
*subscribe_pending = true;
} else {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Received route without pending subscribe");
return false;
}
}
return true;
}
bool BgpXmppChannel::ProcessMcastItem(string vrf_name,
const pugi::xml_node &node, bool add_change) {
McastItemType item;
item.Clear();
if (!item.XmlParse(node)) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Invalid multicast route message received");
return false;
}
if (item.entry.nlri.af != BgpAf::IPv4) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Unsupported address family " << item.entry.nlri.af <<
" for multicast route");
return false;
}
if (item.entry.nlri.safi != BgpAf::Mcast) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name, SandeshLevel::SYS_WARN,
BGP_LOG_FLAG_ALL, "Unsupported subsequent address family " <<
item.entry.nlri.safi << " for multicast route");
return false;
}
error_code error;
IpAddress grp_address = IpAddress::from_string("0.0.0.0", error);
if (!item.entry.nlri.group.empty()) {
if (!XmppDecodeAddress(item.entry.nlri.af,
item.entry.nlri.group, &grp_address, false)) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Bad group address " << item.entry.nlri.group);
return false;
}
}
IpAddress src_address = IpAddress::from_string("0.0.0.0", error);
if (!item.entry.nlri.source.empty()) {
if (!XmppDecodeAddress(item.entry.nlri.af,
item.entry.nlri.source, &src_address, true)) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Bad source address " << item.entry.nlri.source);
return false;
}
}
bool subscribe_pending;
int instance_id;
uint64_t subscription_gen_id;
BgpTable *table;
if (!VerifyMembership(vrf_name, Address::ERMVPN, &table, &instance_id,
&subscription_gen_id, &subscribe_pending)) {
channel_->Close();
return false;
}
// Build the key to the Multicast DBTable
RouteDistinguisher mc_rd(peer_->bgp_identifier(), instance_id);
ErmVpnPrefix mc_prefix(ErmVpnPrefix::NativeRoute, mc_rd,
grp_address.to_v4(), src_address.to_v4());
// Build and enqueue a DB request for route-addition
DBRequest req;
req.key.reset(new ErmVpnTable::RequestKey(mc_prefix, peer_.get()));
uint32_t flags = 0;
ExtCommunitySpec ext;
string label_range("none");
if (add_change) {
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
vector<uint32_t> labels;
const McastNextHopsType &inh_list = item.entry.next_hops;
if (inh_list.next_hop.empty()) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Missing next-hop for multicast route " <<
mc_prefix.ToString());
return false;
}
// Agents should send only one next-hop in the item
if (inh_list.next_hop.size() != 1) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"More than one nexthop received for multicast route " <<
mc_prefix.ToString());
return false;
}
McastNextHopsType::const_iterator nit = inh_list.begin();
// Label Allocation item.entry.label by parsing the range
label_range = nit->label;
if (!stringToIntegerList(label_range, "-", labels) ||
labels.size() != 2) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Bad label range " << label_range <<
" for multicast route " << mc_prefix.ToString());
return false;
}
BgpAttrSpec attrs;
LabelBlockPtr lbptr = lb_mgr_->LocateBlock(labels[0], labels[1]);
BgpAttrLabelBlock attr_label(lbptr);
attrs.push_back(&attr_label);
// Next-hop ip address
IpAddress nh_address;
if (!XmppDecodeAddress(nit->af, nit->address, &nh_address)) {
BGP_LOG_PEER_INSTANCE(Peer(), vrf_name,
SandeshLevel::SYS_WARN, BGP_LOG_FLAG_ALL,
"Bad nexthop address " << nit->address <<
" for multicast route " << mc_prefix.ToString());
return false;
}
BgpAttrNextHop nexthop(nh_address.to_v4().to_ulong());
attrs.push_back(&nexthop);
// Process tunnel encapsulation list.
bool no_tunnel_encap = true;
bool no_valid_tunnel_encap = true;
for (McastTunnelEncapsulationListType::const_iterator eit =
nit->tunnel_encapsulation_list.begin();
eit != nit->tunnel_encapsulation_list.end(); ++eit) {
no_tunnel_encap = false;
TunnelEncap tun_encap(*eit);
if (tun_encap.tunnel_encap() == TunnelEncapType::UNSPEC)
continue;
no_valid_tunnel_encap = false;