/
bgp_peer.cc
2615 lines (2267 loc) · 87.7 KB
/
bgp_peer.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_peer.h"
#include <algorithm>
#include <limits>
#include <map>
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
#include "base/task_annotations.h"
#include "bgp/bgp_factory.h"
#include "bgp/bgp_log.h"
#include "bgp/bgp_membership.h"
#include "bgp/bgp_peer_close.h"
#include "bgp/bgp_sandesh.h"
#include "bgp/bgp_server.h"
#include "bgp/bgp_session.h"
#include "bgp/bgp_session_manager.h"
#include "bgp/bgp_peer_types.h"
#include "bgp/community.h"
#include "bgp/ermvpn/ermvpn_table.h"
#include "bgp/evpn/evpn_table.h"
#include "bgp/inet/inet_table.h"
#include "bgp/inet6/inet6_table.h"
#include "bgp/inet6vpn/inet6vpn_table.h"
#include "bgp/l3vpn/inetvpn_table.h"
#include "bgp/mvpn/mvpn_table.h"
#include "bgp/peer_close_manager.h"
#include "bgp/routing-instance/peer_manager.h"
#include "bgp/routing-instance/routing_instance.h"
#include "bgp/routing-policy/routing_policy_match.h"
#include "bgp/rtarget/rtarget_table.h"
#include "bgp/tunnel_encap/tunnel_encap.h"
#include "control-node/control_node.h"
#include "config-client-mgr/config_client_manager.h"
using boost::assign::list_of;
using boost::assign::map_list_of;
using boost::system::error_code;
using boost::tie;
using std::copy;
using std::dec;
using std::map;
using std::numeric_limits;
using std::ostringstream;
using std::string;
using std::vector;
class BgpPeer::PeerStats : public IPeerDebugStats {
public:
explicit PeerStats(BgpPeer *peer)
: peer_(peer) {
}
// Used when peer flaps.
// Reset all counters.
// Socket counters are implicitly cleared because we use a new socket.
virtual void Clear() {
error_stats_ = ErrorStats();
proto_stats_[0] = ProtoStats();
proto_stats_[1] = ProtoStats();
update_stats_[0] = UpdateStats();
update_stats_[1] = UpdateStats();
}
// Printable name
virtual string ToString() const {
return peer_->ToString();
}
// Previous State of the peer
virtual string last_state() const {
return peer_->state_machine()->LastStateName();
}
virtual string last_state_change_at() const {
return peer_->state_machine()->last_state_change_at();
}
// Last error on this peer
virtual string last_error() const {
return peer_->state_machine()->last_notification_in_error();
}
// Last Event on this peer
virtual string last_event() const {
return peer_->state_machine()->last_event();
}
// When was the Last
virtual string last_flap() const {
return peer_->last_flap_at();
}
// Total number of flaps
virtual uint64_t num_flaps() const {
return peer_->flap_count();
}
virtual void GetRxProtoStats(ProtoStats *stats) const {
*stats = proto_stats_[0];
}
virtual void GetTxProtoStats(ProtoStats *stats) const {
*stats = proto_stats_[1];
}
virtual void GetRxRouteUpdateStats(UpdateStats *stats) const {
*stats = update_stats_[0];
}
virtual void GetTxRouteUpdateStats(UpdateStats *stats) const {
*stats = update_stats_[1];
}
virtual void GetRxSocketStats(IPeerDebugStats::SocketStats *stats) const {
if (peer_->session()) {
io::SocketStats socket_stats(peer_->session()->GetSocketStats());
stats->calls = socket_stats.read_calls;
stats->bytes = socket_stats.read_bytes;
}
}
virtual void GetTxSocketStats(IPeerDebugStats::SocketStats *stats) const {
if (peer_->session()) {
io::SocketStats socket_stats(peer_->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 UpdateTxUnreachRoute(uint64_t count) {
update_stats_[1].unreach += count;
}
virtual void UpdateTxReachRoute(uint64_t count) {
update_stats_[1].reach += count;
}
// Do nothing for bgp peers.
virtual void GetRxErrorStats(RxErrorStats *stats) const {
}
virtual void GetRxRouteStats(RxRouteStats *stats) const {
stats->total_path_count = peer_->GetTotalPathCount();
stats->primary_path_count = peer_->GetPrimaryPathCount();
}
private:
friend class BgpPeer;
BgpPeer *peer_;
ErrorStats error_stats_;
ProtoStats proto_stats_[2];
UpdateStats update_stats_[2];
};
class BgpPeer::DeleteActor : public LifetimeActor {
public:
explicit DeleteActor(BgpPeer *peer)
: LifetimeActor(peer->server_->lifetime_manager()),
peer_(peer) {
}
virtual bool MayDelete() const {
CHECK_CONCURRENCY("bgp::Config");
if (!peer_->close_manager_->IsQueueEmpty())
return false;
if (peer_->IsCloseInProgress())
return false;
if (!peer_->state_machine_->IsQueueEmpty())
return false;
if (peer_->prefix_limit_trigger_.IsSet())
return false;
return true;
}
virtual void Shutdown() {
CHECK_CONCURRENCY("bgp::Config");
peer_->Clear(BgpProto::Notification::PeerDeconfigured);
}
virtual void Destroy() {
CHECK_CONCURRENCY("bgp::Config");
peer_->PostCloseRelease();
if (peer_->IsRouterTypeBGPaaS()) {
peer_->server()->decrement_deleting_bgpaas_count();
} else {
peer_->server()->decrement_deleting_count();
}
if (peer_->dscp_listener_id_ >= 0) {
peer_->server()->UnregisterDSCPUpdateCallback(
peer_->dscp_listener_id_);
peer_->dscp_listener_id_ = -1;
}
assert(!peer_->membership_req_pending());
assert(!peer_->close_manager_->IsMembershipInUse());
peer_->rtinstance_->peer_manager()->DestroyIPeer(peer_);
}
private:
BgpPeer *peer_;
};
//
// Constructor for BgpPeerFamilyAttributes.
//
BgpPeerFamilyAttributes::BgpPeerFamilyAttributes(
const BgpNeighborConfig *config,
const BgpFamilyAttributesConfig &family_config) {
if (family_config.loop_count) {
loop_count = family_config.loop_count;
} else {
loop_count = config->loop_count();
}
prefix_limit = family_config.prefix_limit;
idle_timeout = family_config.idle_timeout;
default_tunnel_encap_list = family_config.default_tunnel_encap_list;
if (config->router_type() == "bgpaas-client") {
if (family_config.family == "inet") {
gateway_address = config->gateway_address(Address::INET);
} else if (family_config.family == "inet6") {
gateway_address = config->gateway_address(Address::INET6);
}
}
}
RibExportPolicy BgpPeer::BuildRibExportPolicy(Address::Family family) const {
RibExportPolicy policy;
BgpPeerFamilyAttributes *family_attributes =
family_attributes_list_[family];
if (!family_attributes) {
policy = RibExportPolicy(peer_type_, RibExportPolicy::BGP, peer_as_,
as_override_, peer_close_->IsCloseLongLivedGraceful(),
-1, cluster_id_, local_as_);
} else {
policy = RibExportPolicy(peer_type_, RibExportPolicy::BGP, peer_as_,
as_override_, peer_close_->IsCloseLongLivedGraceful(),
family_attributes->gateway_address,
-1, cluster_id_, family_attributes->default_tunnel_encap_list,
local_as_);
}
if (private_as_action_ == "remove") {
policy.SetRemovePrivatePolicy(false, false, true);
} else if (private_as_action_ == "remove-all") {
policy.SetRemovePrivatePolicy(true, false, true);
} else if (private_as_action_ == "replace-all") {
policy.SetRemovePrivatePolicy(true, true, true);
}
return policy;
}
void BgpPeer::ReceiveEndOfRIB(Address::Family family, size_t msgsize) {
close_manager_->ProcessEORMarkerReceived(family);
eor_receive_timer_[family]->Cancel();
// If EoR for RTarget is received, start registration for other families.
if (family == Address::RTARGET)
RegisterToVpnTables();
}
void BgpPeer::SendEndOfRIBActual(Address::Family family) {
tbb::spin_mutex::scoped_lock lock(spin_mutex_);
// Bail if there's no session for the peer anymore.
if (!session_)
return;
BgpProto::Update update;
uint16_t afi;
uint8_t safi;
tie(afi, safi) = BgpAf::FamilyToAfiSafi(family);
BgpMpNlri *nlri = new BgpMpNlri(BgpAttribute::MPUnreachNlri, afi, safi);
update.path_attributes.push_back(nlri);
uint8_t data[256];
int msgsize = BgpProto::Encode(&update, data, sizeof(data));
assert(msgsize > BgpProto::kMinMessageSize);
session_->Send(data, msgsize, NULL);
inc_tx_end_of_rib();
inc_tx_update();
BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
"EndOfRib marker family " << Address::FamilyToString(family) <<
" size " << msgsize);
}
uint32_t BgpPeer::GetOutputQueueDepth(Address::Family family) const {
BgpTable *table = GetRoutingInstance()->GetTable(family);
return server_->membership_mgr()->GetRibOutQueueDepth(this, table);
}
time_t BgpPeer::GetEorSendTimerElapsedTime() const {
return UTCTimestamp() - eor_send_timer_start_time_;
}
uint32_t BgpPeer::GetEndOfRibReceiveTime(Address::Family family) const {
return family == Address::RTARGET ?
kRouteTargetEndOfRibTimeSecs : server_->GetEndOfRibReceiveTime();
}
bool BgpPeer::IsServerStartingUp() const {
return server_->IsServerStartingUp();
}
bool BgpPeer::IsCloseGraceful() const {
return peer_close_->IsCloseGraceful();
}
time_t BgpPeer::GetRTargetTableLastUpdatedTimeStamp() const {
return server_->GetRTargetTableLastUpdatedTimeStamp();
}
bool BgpPeer::EndOfRibSendTimerExpired(Address::Family family) {
if (!IsReady())
return false;
// Send EoR if wait time has exceeded the configured maximum.
if (GetEorSendTimerElapsedTime() >= server_->GetEndOfRibSendTime()) {
SendEndOfRIBActual(family);
return false;
}
// Defer if output queue has not been fully drained yet.
uint32_t output_depth = GetOutputQueueDepth(family);
if (output_depth) {
eor_send_timer_[family]->Reschedule(kEndOfRibSendRetryTime * 1000);
BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
"EndOfRib Send Timer rescheduled for family " <<
Address::FamilyToString(family) << " to fire after " <<
kEndOfRibSendRetryTime << " second(s) " <<
"due to non-empty output queue (" << output_depth << ")");
return true;
}
// Send EoR if we are not still under [re-]starting phase.
if (!IsServerStartingUp()) {
SendEndOfRIBActual(family);
return false;
}
// Defer if configuration processing is not complete yet.
if (!ConfigClientManager::end_of_rib_computed()) {
eor_send_timer_[family]->Reschedule(kEndOfRibSendRetryTime * 1000);
BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
"EndOfRib Send Timer rescheduled for family " <<
Address::FamilyToString(family) << " to fire after " <<
kEndOfRibSendRetryTime << " second(s) " <<
"as bgp (under restart) has not completed initial configuration"
" processing");
return true;
}
// For all families except route-target, wait for a certain amount of time
// before sending eor as bgp is still in [re-]starting phase (60s).
if (family != Address::RTARGET) {
eor_send_timer_[family]->Reschedule(kEndOfRibSendRetryTime * 1000);
BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
"EndOfRib Send Timer rescheduled for family " <<
Address::FamilyToString(family) << " to fire after " <<
kEndOfRibSendRetryTime << " second(s) " <<
"as bgp is still under [re-]starting phase");
return true;
}
// Defer EoR if any new route-target was added to the table recently (6s).
if (UTCTimestamp() - GetRTargetTableLastUpdatedTimeStamp() <
0.02 * server_->GetEndOfRibSendTime()) {
eor_send_timer_[family]->Reschedule(kEndOfRibSendRetryTime * 1000);
BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
"EndOfRib Send Timer rescheduled for family " <<
Address::FamilyToString(family) << " to fire after " <<
kEndOfRibSendRetryTime << " second(s) " <<
"as new route-targets are still being added to the table");
return true;
}
// Send eor as [re-]starting phase is complete for this family.
SendEndOfRIBActual(family);
return false;
}
void BgpPeer::SendEndOfRIB(Address::Family family) {
eor_send_timer_start_time_ = UTCTimestamp();
BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
"EndOfRib Send Timer scheduled for family " <<
Address::FamilyToString(family) <<
" to fire after " << kEndOfRibSendRetryTime << " second(s)");
eor_send_timer_[family]->Start(kEndOfRibSendRetryTime * 1000,
boost::bind(&BgpPeer::EndOfRibSendTimerExpired, this, family),
boost::bind(&BgpPeer::EndOfRibTimerErrorHandler, this, _1, _2));
}
void BgpPeer::BGPPeerInfoSend(const BgpPeerInfoData &peer_info) const {
BGPPeerInfo::Send(peer_info);
}
bool BgpPeer::CanUseMembershipManager() const {
return !membership_req_pending_;
}
//
// Callback from BgpMembershipManager.
// Update pending membership request count and send EndOfRib for the family
// in question.
//
void BgpPeer::MembershipRequestCallback(BgpTable *table) {
if (close_manager_->IsMembershipInUse()) {
close_manager_->MembershipRequestCallback();
return;
}
assert(membership_req_pending_ > 0);
membership_req_pending_--;
// Resume if CloseManager is waiting to use membership manager.
if (!membership_req_pending_ &&
close_manager_->IsMembershipInWait()) {
close_manager_->MembershipRequest();
}
// Resume close if it was deferred and this is the last pending callback.
// Don't bother sending EndOfRib if close is deferred.
if (defer_close_) {
if (!membership_req_pending_) {
defer_close_ = false;
trigger_.Set();
}
return;
}
SendEndOfRIB(table->family());
}
bool BgpPeer::MembershipPathCallback(DBTablePartBase *tpart, BgpRoute *route,
BgpPath *path) {
return close_manager_->MembershipPathCallback(tpart, route, path);
}
bool BgpPeer::ResumeClose() {
peer_close_->Close(graceful_close_);
graceful_close_ = true;
return true;
}
BgpPeer::BgpPeer(BgpServer *server, RoutingInstance *instance,
const BgpNeighborConfig *config)
: server_(server),
rtinstance_(instance),
peer_key_(config),
peer_port_(config->source_port()),
peer_name_(config->name()),
router_type_(config->router_type()),
config_(config),
index_(server->RegisterPeer(this)),
trigger_(boost::bind(&BgpPeer::ResumeClose, this),
TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
GetTaskInstance()),
prefix_limit_idle_timer_(
TimerManager::CreateTimer(*server->ioservice(),
"BGP prefix limit idle timer",
TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
GetTaskInstance())),
prefix_limit_trigger_(boost::bind(&BgpPeer::CheckPrefixLimits, this),
TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
GetTaskInstance()),
buffer_capacity_(GetBufferCapacity()),
session_(NULL),
keepalive_timer_(TimerManager::CreateTimer(*server->ioservice(),
"BGP keepalive timer",
TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
GetTaskInstance())),
eor_send_timer_start_time_(0),
send_ready_(true),
admin_down_(config->admin_down()),
passive_(config->passive()),
resolve_paths_(config->router_type() == "bgpaas-client"),
as_override_(config->as_override()),
cluster_id_(config->cluster_id()),
origin_override_(config->origin_override()),
defer_close_(false),
graceful_close_(true),
vpn_tables_registered_(false),
hold_time_(config->hold_time()),
local_as_(config->local_as()),
peer_as_(config->peer_as()),
local_bgp_id_(config->local_identifier()),
peer_bgp_id_(0),
family_primary_path_count_(Address::NUM_FAMILIES),
peer_type_((config->peer_as() == config->local_as()) ?
BgpProto::IBGP : BgpProto::EBGP),
state_machine_(BgpObjectFactory::Create<StateMachine>(this)),
peer_close_(BgpObjectFactory::Create<BgpPeerClose>(this)),
peer_stats_(new PeerStats(this)),
deleter_(new DeleteActor(this)),
instance_delete_ref_(this, instance ? instance->deleter() : NULL),
flap_count_(0),
total_flap_count_(0),
last_flap_(0),
dscp_listener_id_(-1),
inuse_authkey_type_(AuthenticationData::NIL) {
buffer_.reserve(buffer_capacity_);
close_manager_.reset(
BgpObjectFactory::Create<PeerCloseManager>(peer_close_.get()));
ostringstream oss1;
oss1 << peer_key_.endpoint.address();
if (peer_key_.endpoint.port() != BgpConfigManager::kDefaultPort)
oss1 << ":" << dec << peer_key_.endpoint.port();
to_str_ = oss1.str();
ostringstream oss2;
if (rtinstance_)
oss2 << rtinstance_->name() << ":";
oss2 << server_->localname() << ":";
oss2 << peer_name();
uve_key_str_ = oss2.str();
if (router_type_ == "control-node" ||
router_type_ == "external-control-node") {
peer_is_control_node_ = true;
} else {
peer_is_control_node_ = false;
}
dscp_listener_id_ = server_->RegisterDSCPUpdateCallback(boost::bind(
&BgpPeer::DSCPUpdateCallback, this, _1));
membership_req_pending_ = 0;
BGP_LOG_PEER(Event, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
BGP_PEER_DIR_NA, "Created");
if (rtinstance_ && peer_name_.find(rtinstance_->name()) == 0) {
peer_basename_ = peer_name_.substr(rtinstance_->name().size() + 1);
} else {
peer_basename_ = peer_name_;
}
for (Address::Family family = Address::UNSPEC;
family < Address::NUM_FAMILIES;
family = static_cast<Address::Family>(family + 1)) {
family_primary_path_count_[family] = 0;
eor_send_timer_[family] =
TimerManager::CreateTimer(*server->ioservice(),
"BGP EoR Send timer for " + Address::FamilyToString(family),
TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
GetTaskInstance());
eor_receive_timer_[family] =
TimerManager::CreateTimer(*server->ioservice(),
"BGP EoR Receive timer for " + Address::FamilyToString(family),
TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
GetTaskInstance());
}
total_path_count_ = 0;
primary_path_count_ = 0;
// Check rtinstance_ to accommodate unit tests.
if (resolve_paths_ && rtinstance_) {
rtinstance_->GetTable(Address::INET)->LocatePathResolver();
rtinstance_->GetTable(Address::INET6)->LocatePathResolver();
}
ProcessEndpointConfig(config);
ProcessAuthKeyChainConfig(config);
ProcessFamilyAttributesConfig(config);
BgpPeerInfoData peer_info;
peer_info.set_name(ToUVEKey());
peer_info.set_admin_down(admin_down_);
peer_info.set_passive(passive_);
peer_info.set_as_override(as_override_);
peer_info.set_origin_override(origin_override_.origin_override);
if (origin_override_.origin_override) {
peer_info.set_route_origin(
BgpAttr::OriginToString(origin_override_.origin));
} else {
peer_info.set_route_origin("-");
}
peer_info.set_router_type(router_type_);
peer_info.set_cluster_id(Ip4Address(cluster_id_).to_string());
peer_info.set_peer_type(
PeerType() == BgpProto::IBGP ? "internal" : "external");
peer_info.set_local_asn(local_as_);
peer_info.set_peer_asn(peer_as_);
peer_info.set_peer_port(peer_port_);
peer_info.set_hold_time(hold_time_);
peer_info.set_local_id(local_bgp_id_);
peer_info.set_configured_families(configured_families_);
peer_info.set_peer_address(peer_key_.endpoint.address().to_string());
BGPPeerInfoSend(peer_info);
}
BgpPeer::~BgpPeer() {
assert(!close_manager()->IsCloseInProgress());
assert(!IsCloseInProgress());
assert(GetTotalPathCount() == 0);
STLDeleteValues(&family_attributes_list_);
ClearListenSocketAuthKey();
BgpPeerInfoData peer_info;
peer_info.set_name(ToUVEKey());
peer_info.set_deleted(true);
BGPPeerInfoSend(peer_info);
PeerStatsData peer_stats_data;
peer_stats_data.set_name(ToUVEKey());
peer_stats_data.set_deleted(true);
PeerStatsUve::Send(peer_stats_data, "ObjectBgpPeer");
PeerFlapData peer_flap_data;
peer_flap_data.set_name(ToUVEKey());
peer_flap_data.set_deleted(true);
PeerFlap::Send(peer_flap_data, "ObjectBgpPeer");
BGP_LOG_PEER(Event, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
BGP_PEER_DIR_NA, "Deleted");
}
void BgpPeer::Initialize() {
if (!admin_down_)
state_machine_->Initialize();
}
size_t BgpPeer::GetBufferCapacity() const {
// For testing only - configure through environment variable.
char *buffer_capacity_str = getenv("BGP_PEER_BUFFER_SIZE");
if (buffer_capacity_str) {
size_t env_buffer_capacity = strtoul(buffer_capacity_str, NULL, 0);
if (env_buffer_capacity < kMinBufferCapacity)
env_buffer_capacity = kMinBufferCapacity;
if (env_buffer_capacity > kMaxBufferCapacity)
env_buffer_capacity = kMaxBufferCapacity;
return env_buffer_capacity;
}
// Return internal default based on peer router-type.
if (IsRouterTypeBGPaaS()) {
return kMinBufferCapacity;
} else {
return kMaxBufferCapacity;
}
}
bool BgpPeer::CheckSplitHorizon(uint32_t server_cluster_id,
uint32_t ribout_cid) const {
if (PeerType() == BgpProto::IBGP) {
// check if router is a route reflector
if (!server_cluster_id) return true;
// check if received from client or non-client by comparing the clusterId
// of router with that of peer from which we this route is received
if (server_cluster_id != cluster_id_) {
// If received from non-client, reflect to all the clients only
if (ribout_cid && ribout_cid != server_cluster_id) {
return true;
}
}
}
return false;
}
void BgpPeer::NotifyEstablished(bool established) {
if (established) {
if (IsRouterTypeBGPaaS()) {
server_->IncrementUpBgpaasPeerCount();
} else {
server_->IncrementUpPeerCount();
}
} else {
if (IsRouterTypeBGPaaS()) {
server_->DecrementUpBgpaasPeerCount();
} else {
server_->DecrementUpPeerCount();
}
}
}
void BgpPeer::BindLocalEndpoint(BgpSession *session) {
}
// Just return the first entry for now.
bool BgpPeer::GetBestAuthKey(AuthenticationKey *auth_key,
KeyType *key_type) const {
if (auth_data_.Empty()) {
return false;
}
assert(auth_key);
AuthenticationData::const_iterator iter = auth_data_.begin();
*auth_key = *iter;
*key_type = auth_data_.key_type();
return true;
}
bool BgpPeer::ProcessAuthKeyChainConfig(const BgpNeighborConfig *config) {
const AuthenticationData &input_auth_data = config->auth_data();
if (auth_data_ == input_auth_data) {
return false;
}
auth_data_ = input_auth_data;
return InstallAuthKeys();
}
bool BgpPeer::InstallAuthKeys() {
if (!PeerAddress()) {
return false;
}
AuthenticationKey auth_key;
KeyType key_type;
bool valid = GetBestAuthKey(&auth_key, &key_type);
if (valid) {
if (key_type == AuthenticationData::MD5) {
LogInstallAuthKeys("Listen", "add", auth_key, key_type);
SetListenSocketAuthKey(auth_key, key_type);
SetInuseAuthKeyInfo(auth_key, key_type);
}
} else {
// If there are no valid available keys but an older one is currently
// installed, un-install it.
if (inuse_authkey_type_ == AuthenticationData::MD5) {
LogInstallAuthKeys("Listen", "delete", inuse_auth_key_,
inuse_authkey_type_);
ClearListenSocketAuthKey();
// Resetting the key information must be done last.
ResetInuseAuthKeyInfo();
}
}
return true;
}
void BgpPeer::SetInuseAuthKeyInfo(const AuthenticationKey &key, KeyType type) {
inuse_auth_key_ = key;
inuse_authkey_type_ = type;
}
void BgpPeer::ResetInuseAuthKeyInfo() {
inuse_auth_key_.Reset();
inuse_authkey_type_ = AuthenticationData::NIL;
}
void BgpPeer::SetListenSocketAuthKey(const AuthenticationKey &auth_key,
KeyType key_type) {
if (key_type == AuthenticationData::MD5) {
server_->session_manager()->
SetListenSocketMd5Option(PeerAddress(), auth_key.value);
}
}
void BgpPeer::ClearListenSocketAuthKey() {
if (inuse_authkey_type_ == AuthenticationData::MD5) {
server_->session_manager()->SetListenSocketMd5Option(PeerAddress(), "");
}
}
void BgpPeer::SetSessionSocketAuthKey(TcpSession *session) {
if ((inuse_authkey_type_ == AuthenticationData::MD5) && PeerAddress()) {
assert(!inuse_auth_key_.value.empty());
LogInstallAuthKeys("Session", "add", inuse_auth_key_,
inuse_authkey_type_);
session->SetMd5SocketOption(PeerAddress(), inuse_auth_key_.value);
}
}
void BgpPeer::SetSessionSocketOptionDscp(TcpSession *session) {
uint8_t dscp_value = server_->global_qos()->control_dscp();
if (!session->socket()) {
return;
}
if (dscp_value != 0xFF) {
session->SetDscpSocketOption(server_->global_qos()->control_dscp());
}
}
string BgpPeer::GetInuseAuthKeyValue() const {
return inuse_auth_key_.value;
}
void BgpPeer::LogInstallAuthKeys(const string &socket_name,
const string &oper, const AuthenticationKey &auth_key,
KeyType key_type) {
string logstr = socket_name + " socket kernel " + oper + " of key id "
+ integerToString(auth_key.id) + ", type "
+ AuthenticationData::KeyTypeToString(key_type)
+ ", peer " + peer_name_;
BGP_LOG_PEER(Config, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
BGP_PEER_DIR_NA, logstr);
}
//
// Check if the configured prefix limit for any address family has been
// exceeded. If yes, clear the peer by sending a notification with a cease
// subcode of MaxPrefixes.
//
bool BgpPeer::CheckPrefixLimits() {
RetryDelete();
if (!IsReady())
return true;
for (size_t idx = Address::UNSPEC; idx < Address::NUM_FAMILIES; ++idx) {
BgpPeerFamilyAttributes *family_attributes =
family_attributes_list_[idx];
if (!family_attributes || family_attributes->prefix_limit == 0)
continue;
if (family_primary_path_count_[idx] <= family_attributes->prefix_limit)
continue;
Clear(BgpProto::Notification::MaxPrefixes);
StartPrefixLimitIdleTimer(family_attributes->idle_timeout * 1000);
break;
}
return true;
}
//
// Process family attributes configuration and update the family attributes
// list.
//
// Return true is there's a change, false otherwise.
//
bool BgpPeer::ProcessFamilyAttributesConfig(const BgpNeighborConfig *config) {
FamilyAttributesList family_attributes_list(Address::NUM_FAMILIES);
BOOST_FOREACH(const BgpFamilyAttributesConfig family_config,
config->family_attributes_list()) {
Address::Family family =
Address::FamilyFromString(family_config.family);
assert(family != Address::UNSPEC);
BgpPeerFamilyAttributes *family_attributes =
new BgpPeerFamilyAttributes(config, family_config);
family_attributes_list[family] = family_attributes;
}
int ret = STLSortedCompare(
family_attributes_list.begin(), family_attributes_list.end(),
family_attributes_list_.begin(), family_attributes_list_.end(),
BgpPeerFamilyAttributesCompare());
STLDeleteValues(&family_attributes_list_);
family_attributes_list_ = family_attributes_list;
configured_families_ = config->GetAddressFamilies();
return (ret != 0);
}
void BgpPeer::ProcessEndpointConfig(const BgpNeighborConfig *config) {
if (config->router_type() == "bgpaas-client") {
endpoint_ = TcpSession::Endpoint(Ip4Address(), config->source_port());
} else {
endpoint_ = TcpSession::Endpoint();
}
}
void BgpPeer::TriggerPrefixLimitCheck() const {
prefix_limit_trigger_.Set();
}
void BgpPeer::ConfigUpdate(const BgpNeighborConfig *config) {
if (IsDeleted())
return;
config_ = config;
// During peer deletion, configuration gets completely deleted. In that
// case, there is no need to update the rest and flap the peer.
if (!config_)
return;
bool clear_session = false;
bool admin_down_changed = false;
BgpPeerInfoData peer_info;
peer_info.set_name(ToUVEKey());
if (admin_down_ != config->admin_down()) {
SetAdminState(config->admin_down());
peer_info.set_admin_down(admin_down_);
admin_down_changed = true;
}
if (passive_ != config->passive()) {
passive_ = config->passive();
peer_info.set_passive(passive_);
clear_session = true;
}
if (as_override_ != config->as_override()) {
as_override_ = config->as_override();
peer_info.set_as_override(as_override_);
clear_session = true;
}
if (cluster_id_ != config->cluster_id()) {
cluster_id_ = config->cluster_id();
peer_info.set_cluster_id(Ip4Address(cluster_id_).to_string());
clear_session = true;
}
OriginOverride origin_override(config->origin_override());
if (origin_override_ != origin_override) {
origin_override_ = origin_override;
peer_info.set_origin_override(origin_override_.origin_override);
if (origin_override_.origin_override) {
peer_info.set_route_origin(config->origin_override().origin);
} else {
peer_info.set_route_origin("-");
}
clear_session = true;
}
if (router_type_ != config->router_type()) {
router_type_ = config->router_type();
peer_info.set_router_type(router_type_);
resolve_paths_ = (config->router_type() == "bgpaas-client");
clear_session = true;
}
if (router_type_ == "control-node" ||
router_type_ == "external-control-node") {
peer_is_control_node_ = true;
} else {
peer_is_control_node_ = false;
}
// Check if there is any change in the peer address.
// If the peer address is changing, remove the key for the older address.
// Update with the new peer address and then process the key chain info
// for the new peer below.
BgpPeerKey key(config);
if (peer_key_ != key) {
ClearListenSocketAuthKey();
peer_key_ = key;
peer_info.set_peer_address(peer_key_.endpoint.address().to_string());
clear_session = true;
}
if (ProcessAuthKeyChainConfig(config)) {
clear_session = true;
}
if (peer_port_ != config->source_port()) {
peer_port_ = config->source_port();
peer_info.set_peer_port(peer_port_);
clear_session = true;
}
ProcessEndpointConfig(config);
if (local_as_ != config->local_as()) {
BGP_LOG_STR(BgpConfig, SandeshLevel::SYS_DEBUG,
BGP_LOG_FLAG_SYSLOG,
"Updated Local Autonomous System from " <<
local_as_ << " to " <<
config->local_as());
local_as_ = config->local_as();
peer_info.set_local_asn(local_as_);
clear_session = true;
}
if (hold_time_ != config->hold_time()) {
BGP_LOG_STR(BgpConfig, SandeshLevel::SYS_DEBUG,
BGP_LOG_FLAG_SYSLOG,
"Updated Hold Time from " <<
hold_time_ << " to " <<
config->hold_time());
hold_time_ = config->hold_time();
peer_info.set_hold_time(hold_time_);
clear_session = true;
}
if (peer_as_ != config->peer_as()) {
BGP_LOG_STR(BgpConfig, SandeshLevel::SYS_DEBUG,
BGP_LOG_FLAG_SYSLOG,
"Updated Peer Autonomous System from " <<
peer_as_ << " to " <<
config->peer_as());
peer_as_ = config->peer_as();
peer_info.set_peer_asn(peer_as_);
clear_session = true;
}
boost::system::error_code ec;
uint32_t local_bgp_id = config->local_identifier();
if (local_bgp_id_ != local_bgp_id) {
local_bgp_id_ = local_bgp_id;
peer_info.set_local_id(local_bgp_id_);
clear_session = true;
}
BgpProto::BgpPeerType old_type = PeerType();
peer_type_ = (peer_as_ == local_as_) ? BgpProto::IBGP : BgpProto::EBGP;
if (old_type != PeerType()) {
peer_info.set_peer_type(
PeerType() == BgpProto::IBGP ? "internal" : "external");
clear_session = true;
}