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_peer.h"
7 :
8 : #include <algorithm>
9 : #include <limits>
10 : #include <map>
11 :
12 : #include <boost/assign/list_of.hpp>
13 : #include <boost/foreach.hpp>
14 : #include <boost/tuple/tuple.hpp>
15 :
16 : #include "base/set_util.h"
17 : #include "base/task_annotations.h"
18 : #include "bgp/bgp_factory.h"
19 : #include "bgp/bgp_log.h"
20 : #include "bgp/bgp_membership.h"
21 : #include "bgp/bgp_peer_close.h"
22 : #include "bgp/bgp_sandesh.h"
23 : #include "bgp/bgp_server.h"
24 : #include "bgp/bgp_session.h"
25 : #include "bgp/bgp_session_manager.h"
26 : #include "bgp/bgp_peer_types.h"
27 : #include "bgp/community.h"
28 : #include "bgp/ermvpn/ermvpn_table.h"
29 : #include "bgp/evpn/evpn_table.h"
30 : #include "bgp/inet/inet_table.h"
31 : #include "bgp/inet6/inet6_table.h"
32 : #include "bgp/inet6vpn/inet6vpn_table.h"
33 : #include "bgp/l3vpn/inetvpn_table.h"
34 : #include "bgp/mvpn/mvpn_table.h"
35 : #include "bgp/peer_close_manager.h"
36 : #include "bgp/routing-instance/peer_manager.h"
37 : #include "bgp/routing-instance/routing_instance.h"
38 : #include "bgp/routing-policy/routing_policy_match.h"
39 : #include "bgp/rtarget/rtarget_table.h"
40 : #include "bgp/tunnel_encap/tunnel_encap.h"
41 : #include "control-node/control_node.h"
42 : #include "config-client-mgr/config_client_manager.h"
43 : using boost::assign::list_of;
44 : using boost::assign::map_list_of;
45 : using boost::system::error_code;
46 : using boost::tie;
47 : using std::copy;
48 : using std::dec;
49 : using std::map;
50 : using std::numeric_limits;
51 : using std::ostringstream;
52 : using std::string;
53 : using std::vector;
54 :
55 : class BgpPeer::PeerStats : public IPeerDebugStats {
56 : public:
57 32 : explicit PeerStats(BgpPeer *peer)
58 160 : : peer_(peer) {
59 32 : }
60 :
61 : // Used when peer flaps.
62 : // Reset all counters.
63 : // Socket counters are implicitly cleared because we use a new socket.
64 80 : virtual void Clear() {
65 80 : error_stats_ = ErrorStats();
66 80 : proto_stats_[0] = ProtoStats();
67 80 : proto_stats_[1] = ProtoStats();
68 80 : update_stats_[0] = UpdateStats();
69 80 : update_stats_[1] = UpdateStats();
70 80 : }
71 :
72 : // Printable name
73 0 : virtual string ToString() const {
74 0 : return peer_->ToString();
75 : }
76 : // Previous State of the peer
77 0 : virtual string last_state() const {
78 0 : return peer_->state_machine()->LastStateName();
79 : }
80 0 : virtual string last_state_change_at() const {
81 0 : return peer_->state_machine()->last_state_change_at();
82 : }
83 : // Last error on this peer
84 0 : virtual string last_error() const {
85 0 : return peer_->state_machine()->last_notification_in_error();
86 : }
87 : // Last Event on this peer
88 0 : virtual string last_event() const {
89 0 : return peer_->state_machine()->last_event();
90 : }
91 :
92 : // When was the Last
93 0 : virtual string last_flap() const {
94 0 : return peer_->last_flap_at();
95 : }
96 :
97 : // Total number of flaps
98 0 : virtual uint64_t num_flaps() const {
99 0 : return peer_->flap_count();
100 : }
101 :
102 0 : virtual void GetRxProtoStats(ProtoStats *stats) const {
103 0 : *stats = proto_stats_[0];
104 0 : }
105 :
106 0 : virtual void GetTxProtoStats(ProtoStats *stats) const {
107 0 : *stats = proto_stats_[1];
108 0 : }
109 :
110 0 : virtual void GetRxRouteUpdateStats(UpdateStats *stats) const {
111 0 : *stats = update_stats_[0];
112 0 : }
113 :
114 0 : virtual void GetTxRouteUpdateStats(UpdateStats *stats) const {
115 0 : *stats = update_stats_[1];
116 0 : }
117 :
118 0 : virtual void GetRxSocketStats(IPeerDebugStats::SocketStats *stats) const {
119 0 : if (peer_->session()) {
120 0 : const io::SocketStats &socket_stats = peer_->session()->GetSocketStats();
121 0 : stats->calls = socket_stats.read_calls;
122 0 : stats->bytes = socket_stats.read_bytes;
123 : }
124 0 : }
125 :
126 0 : virtual void GetTxSocketStats(IPeerDebugStats::SocketStats *stats) const {
127 0 : if (peer_->session()) {
128 0 : const io::SocketStats &socket_stats = peer_->session()->GetSocketStats();
129 0 : stats->calls = socket_stats.write_calls;
130 0 : stats->bytes = socket_stats.write_bytes;
131 0 : stats->blocked_count = socket_stats.write_blocked;
132 0 : stats->blocked_duration_usecs =
133 0 : socket_stats.write_blocked_duration_usecs;
134 : }
135 0 : }
136 :
137 10391 : virtual void UpdateTxUnreachRoute(uint64_t count) {
138 10391 : update_stats_[1].unreach += count;
139 10391 : }
140 :
141 10391 : virtual void UpdateTxReachRoute(uint64_t count) {
142 10391 : update_stats_[1].reach += count;
143 10391 : }
144 :
145 : // Do nothing for bgp peers.
146 0 : virtual void GetRxErrorStats(RxErrorStats *stats) const {
147 0 : }
148 :
149 0 : virtual void GetRxRouteStats(RxRouteStats *stats) const {
150 0 : stats->total_path_count = peer_->GetTotalPathCount();
151 0 : stats->primary_path_count = peer_->GetPrimaryPathCount();
152 0 : }
153 :
154 : private:
155 : friend class BgpPeer;
156 :
157 : BgpPeer *peer_;
158 : ErrorStats error_stats_;
159 : ProtoStats proto_stats_[2];
160 : UpdateStats update_stats_[2];
161 : };
162 :
163 : class BgpPeer::DeleteActor : public LifetimeActor {
164 : public:
165 32 : explicit DeleteActor(BgpPeer *peer)
166 32 : : LifetimeActor(peer->server_->lifetime_manager()),
167 32 : peer_(peer) {
168 32 : }
169 :
170 64 : virtual bool MayDelete() const {
171 64 : CHECK_CONCURRENCY("bgp::Config");
172 64 : if (!peer_->close_manager_->IsQueueEmpty())
173 0 : return false;
174 64 : if (peer_->IsCloseInProgress())
175 0 : return false;
176 64 : if (!peer_->state_machine_->IsQueueEmpty())
177 32 : return false;
178 32 : if (peer_->prefix_limit_trigger_.IsSet())
179 0 : return false;
180 32 : return true;
181 : }
182 :
183 32 : virtual void Shutdown() {
184 32 : CHECK_CONCURRENCY("bgp::Config");
185 32 : peer_->Clear(BgpProto::Notification::PeerDeconfigured);
186 32 : }
187 :
188 32 : virtual void Destroy() {
189 32 : CHECK_CONCURRENCY("bgp::Config");
190 32 : peer_->PostCloseRelease();
191 32 : if (peer_->IsRouterTypeBGPaaS()) {
192 0 : peer_->server()->decrement_deleting_bgpaas_count();
193 : } else {
194 32 : peer_->server()->decrement_deleting_count();
195 : }
196 32 : if (peer_->dscp_listener_id_ >= 0) {
197 32 : peer_->server()->UnregisterDSCPUpdateCallback(
198 32 : peer_->dscp_listener_id_);
199 32 : peer_->dscp_listener_id_ = -1;
200 : }
201 32 : if (peer_->instance_op_ >= 0) {
202 0 : peer_->server()->routing_instance_mgr()->
203 0 : UnregisterInstanceOpCallback(peer_->instance_op_);
204 0 : peer_->instance_op_ = -1;
205 : }
206 32 : if (peer_->asn_listener_id_ >= 0) {
207 0 : peer_->server()->UnregisterASNUpdateCallback(
208 0 : peer_->asn_listener_id_);
209 0 : peer_->asn_listener_id_ = -1;
210 : }
211 32 : assert(!peer_->membership_req_pending());
212 32 : assert(!peer_->close_manager_->IsMembershipInUse());
213 32 : peer_->rtinstance_->peer_manager()->DestroyIPeer(peer_);
214 32 : }
215 :
216 : private:
217 : BgpPeer *peer_;
218 : };
219 :
220 : //
221 : // Constructor for BgpPeerFamilyAttributes.
222 : //
223 320 : BgpPeerFamilyAttributes::BgpPeerFamilyAttributes(
224 : const BgpNeighborConfig *config,
225 320 : const BgpFamilyAttributesConfig &family_config) {
226 320 : if (family_config.loop_count) {
227 0 : loop_count = family_config.loop_count;
228 : } else {
229 320 : loop_count = config->loop_count();
230 : }
231 320 : prefix_limit = family_config.prefix_limit;
232 320 : idle_timeout = family_config.idle_timeout;
233 320 : default_tunnel_encap_list = family_config.default_tunnel_encap_list;
234 :
235 320 : if (config->router_type() == "bgpaas-client") {
236 0 : if (family_config.family == "inet") {
237 0 : gateway_address = config->gateway_address(Address::INET);
238 0 : } else if (family_config.family == "inet6") {
239 0 : gateway_address = config->gateway_address(Address::INET6);
240 : }
241 : }
242 320 : }
243 :
244 344 : RibExportPolicy BgpPeer::BuildRibExportPolicy(Address::Family family) const {
245 344 : RibExportPolicy policy;
246 : BgpPeerFamilyAttributes *family_attributes =
247 344 : family_attributes_list_[family];
248 344 : if (!family_attributes) {
249 0 : policy = RibExportPolicy(peer_type_, RibExportPolicy::BGP, peer_as_,
250 0 : as_override_, peer_close_->IsCloseLongLivedGraceful(),
251 0 : as4_supported_, -1, cluster_id_, local_as_);
252 : } else {
253 344 : policy = RibExportPolicy(peer_type_, RibExportPolicy::BGP, peer_as_,
254 344 : as_override_, peer_close_->IsCloseLongLivedGraceful(),
255 344 : as4_supported_, family_attributes->gateway_address,
256 344 : -1, cluster_id_, family_attributes->default_tunnel_encap_list,
257 688 : local_as_);
258 : }
259 :
260 344 : if (private_as_action_ == "remove") {
261 0 : policy.SetRemovePrivatePolicy(false, false, true);
262 344 : } else if (private_as_action_ == "remove-all") {
263 0 : policy.SetRemovePrivatePolicy(true, false, true);
264 344 : } else if (private_as_action_ == "replace-all") {
265 0 : policy.SetRemovePrivatePolicy(true, true, true);
266 : }
267 :
268 344 : return policy;
269 0 : }
270 :
271 348 : void BgpPeer::ReceiveEndOfRIB(Address::Family family, size_t msgsize) {
272 348 : close_manager_->ProcessEORMarkerReceived(family);
273 348 : eor_receive_timer_[family]->Cancel();
274 :
275 : // If EoR for RTarget is received, start registration for other families.
276 348 : if (family == Address::RTARGET)
277 74 : RegisterToVpnTables();
278 348 : }
279 :
280 356 : void BgpPeer::SendEndOfRIBActual(Address::Family family) {
281 356 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
282 :
283 : // Bail if there's no session for the peer anymore.
284 356 : if (!session_)
285 0 : return;
286 :
287 356 : BgpProto::Update update;
288 : uint16_t afi;
289 : uint8_t safi;
290 356 : tie(afi, safi) = BgpAf::FamilyToAfiSafi(family);
291 356 : BgpMpNlri *nlri = new BgpMpNlri(BgpAttribute::MPUnreachNlri, afi, safi);
292 356 : update.path_attributes.push_back(nlri);
293 : uint8_t data[256];
294 712 : int msgsize = BgpProto::Encode(&update, data, sizeof(data), NULL,
295 356 : Is4ByteAsSupported());
296 356 : assert(msgsize > BgpProto::kMinMessageSize);
297 356 : session_->Send(data, msgsize, NULL);
298 356 : inc_tx_end_of_rib();
299 356 : inc_tx_update();
300 356 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
301 : BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
302 : "EndOfRib marker family " << Address::FamilyToString(family) <<
303 : " size " << msgsize);
304 356 : }
305 :
306 0 : uint32_t BgpPeer::GetOutputQueueDepth(Address::Family family) const {
307 0 : BgpTable *table = GetRoutingInstance()->GetTable(family);
308 0 : return server_->membership_mgr()->GetRibOutQueueDepth(this, table);
309 : }
310 :
311 0 : time_t BgpPeer::GetEorSendTimerElapsedTime() const {
312 0 : return UTCTimestamp() - eor_send_timer_start_time_;
313 : }
314 :
315 664 : uint32_t BgpPeer::GetEndOfRibReceiveTime(Address::Family family) const {
316 664 : return family == Address::RTARGET ?
317 664 : kRouteTargetEndOfRibTimeSecs : server_->GetEndOfRibReceiveTime();
318 : }
319 :
320 188 : bool BgpPeer::IsServerStartingUp() const {
321 188 : return server_->IsServerStartingUp();
322 : }
323 :
324 0 : bool BgpPeer::IsCloseGraceful() const {
325 0 : return peer_close_->IsCloseGraceful();
326 : }
327 :
328 0 : time_t BgpPeer::GetRTargetTableLastUpdatedTimeStamp() const {
329 0 : return server_->GetRTargetTableLastUpdatedTimeStamp();
330 : }
331 :
332 0 : bool BgpPeer::EndOfRibSendTimerExpired(Address::Family family) {
333 0 : if (!IsReady())
334 0 : return false;
335 :
336 : // Send EoR if wait time has exceeded the configured maximum.
337 0 : if (GetEorSendTimerElapsedTime() >= server_->GetEndOfRibSendTime()) {
338 0 : SendEndOfRIBActual(family);
339 0 : return false;
340 : }
341 :
342 : // Defer if output queue has not been fully drained yet.
343 0 : uint32_t output_depth = GetOutputQueueDepth(family);
344 0 : if (output_depth) {
345 0 : eor_send_timer_[family]->Reschedule(kEndOfRibSendRetryTime * 1000);
346 0 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
347 : BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
348 : "EndOfRib Send Timer rescheduled for family " <<
349 : Address::FamilyToString(family) << " to fire after " <<
350 : kEndOfRibSendRetryTime << " second(s) " <<
351 : "due to non-empty output queue (" << output_depth << ")");
352 0 : return true;
353 : }
354 :
355 : // Send EoR if we are not still under [re-]starting phase.
356 0 : if (!IsServerStartingUp()) {
357 0 : SendEndOfRIBActual(family);
358 0 : return false;
359 : }
360 :
361 : // Defer if configuration processing is not complete yet.
362 0 : if (!ConfigClientManager::end_of_rib_computed()) {
363 0 : eor_send_timer_[family]->Reschedule(kEndOfRibSendRetryTime * 1000);
364 0 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
365 : BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
366 : "EndOfRib Send Timer rescheduled for family " <<
367 : Address::FamilyToString(family) << " to fire after " <<
368 : kEndOfRibSendRetryTime << " second(s) " <<
369 : "as bgp (under restart) has not completed initial configuration"
370 : " processing");
371 0 : return true;
372 : }
373 :
374 : // For all families except route-target, wait for a certain amount of time
375 : // before sending eor as bgp is still in [re-]starting phase (60s).
376 0 : if (family != Address::RTARGET) {
377 0 : eor_send_timer_[family]->Reschedule(kEndOfRibSendRetryTime * 1000);
378 0 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
379 : BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
380 : "EndOfRib Send Timer rescheduled for family " <<
381 : Address::FamilyToString(family) << " to fire after " <<
382 : kEndOfRibSendRetryTime << " second(s) " <<
383 : "as bgp is still under [re-]starting phase");
384 0 : return true;
385 : }
386 :
387 : // Defer EoR if any new route-target was added to the table recently (6s).
388 0 : if (UTCTimestamp() - GetRTargetTableLastUpdatedTimeStamp() <
389 0 : 0.02 * server_->GetEndOfRibSendTime()) {
390 0 : eor_send_timer_[family]->Reschedule(kEndOfRibSendRetryTime * 1000);
391 0 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
392 : BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
393 : "EndOfRib Send Timer rescheduled for family " <<
394 : Address::FamilyToString(family) << " to fire after " <<
395 : kEndOfRibSendRetryTime << " second(s) " <<
396 : "as new route-targets are still being added to the table");
397 0 : return true;
398 : }
399 :
400 : // Send eor as [re-]starting phase is complete for this family.
401 0 : SendEndOfRIBActual(family);
402 0 : return false;
403 : }
404 :
405 0 : void BgpPeer::SendEndOfRIB(Address::Family family) {
406 0 : eor_send_timer_start_time_ = UTCTimestamp();
407 0 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
408 : BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
409 : "EndOfRib Send Timer scheduled for family " <<
410 : Address::FamilyToString(family) <<
411 : " to fire after " << kEndOfRibSendRetryTime << " second(s)");
412 0 : eor_send_timer_[family]->Start(kEndOfRibSendRetryTime * 1000,
413 : boost::bind(&BgpPeer::EndOfRibSendTimerExpired, this, family),
414 : boost::bind(&BgpPeer::EndOfRibTimerErrorHandler, this, _1, _2));
415 0 : }
416 :
417 328 : void BgpPeer::BGPPeerInfoSend(const BgpPeerInfoData &peer_info) const {
418 328 : assert(!peer_info.get_name().empty());
419 328 : BGP_UVE_SEND(BGPPeerInfo, peer_info);
420 328 : }
421 :
422 96 : bool BgpPeer::CanUseMembershipManager() const {
423 96 : return !membership_req_pending_;
424 : }
425 :
426 : //
427 : // Callback from BgpMembershipManager.
428 : // Update pending membership request count and send EndOfRib for the family
429 : // in question.
430 : //
431 784 : void BgpPeer::MembershipRequestCallback(BgpTable *table) {
432 784 : if (close_manager_->IsMembershipInUse()) {
433 440 : close_manager_->MembershipRequestCallback();
434 440 : return;
435 : }
436 :
437 344 : assert(membership_req_pending_ > 0);
438 344 : membership_req_pending_--;
439 :
440 : // Resume if CloseManager is waiting to use membership manager.
441 469 : if (!membership_req_pending_ &&
442 125 : close_manager_->IsMembershipInWait()) {
443 8 : close_manager_->MembershipRequest();
444 : }
445 :
446 : // Resume close if it was deferred and this is the last pending callback.
447 : // Don't bother sending EndOfRib if close is deferred.
448 344 : if (defer_close_) {
449 28 : if (!membership_req_pending_) {
450 16 : defer_close_ = false;
451 16 : trigger_.Set();
452 : }
453 28 : return;
454 : }
455 :
456 316 : SendEndOfRIB(table->family());
457 : }
458 :
459 5370 : bool BgpPeer::MembershipPathCallback(DBTablePartBase *tpart, BgpRoute *route,
460 : BgpPath *path) {
461 5370 : return close_manager_->MembershipPathCallback(tpart, route, path);
462 : }
463 :
464 16 : bool BgpPeer::ResumeClose() {
465 16 : peer_close_->Close(graceful_close_);
466 16 : graceful_close_ = true;
467 16 : return true;
468 : }
469 :
470 32 : BgpPeer::BgpPeer(BgpServer *server, RoutingInstance *instance,
471 32 : const BgpNeighborConfig *config)
472 32 : : server_(server),
473 32 : rtinstance_(instance),
474 32 : peer_key_(config),
475 32 : peer_port_(config->source_port()),
476 32 : peer_name_(config->name()),
477 32 : router_type_(config->router_type()),
478 32 : config_(config),
479 32 : index_(server->RegisterPeer(this)),
480 32 : trigger_(boost::bind(&BgpPeer::ResumeClose, this),
481 : TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
482 : GetTaskInstance()),
483 32 : prefix_limit_idle_timer_(
484 32 : TimerManager::CreateTimer(*server->ioservice(),
485 : "BGP prefix limit idle timer",
486 : TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
487 : GetTaskInstance())),
488 32 : prefix_limit_trigger_(boost::bind(&BgpPeer::CheckPrefixLimits, this),
489 : TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
490 : GetTaskInstance()),
491 32 : buffer_capacity_(GetBufferCapacity()),
492 32 : session_(NULL),
493 32 : keepalive_timer_(TimerManager::CreateTimer(*server->ioservice(),
494 : "BGP keepalive timer",
495 : TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
496 : GetTaskInstance())),
497 32 : eor_send_timer_start_time_(0),
498 32 : send_ready_(true),
499 32 : admin_down_(config->admin_down()),
500 32 : passive_(config->passive()),
501 32 : resolve_paths_(config->router_type() == "bgpaas-client"),
502 32 : as_override_(config->as_override()),
503 32 : cluster_id_(config->cluster_id()),
504 32 : origin_override_(config->origin_override()),
505 32 : defer_close_(false),
506 32 : graceful_close_(true),
507 32 : as4_supported_(false),
508 32 : vpn_tables_registered_(false),
509 32 : hold_time_(config->hold_time()),
510 32 : local_as_(config->local_as()),
511 32 : peer_as_(config->peer_as()),
512 32 : local_bgp_id_(config->local_identifier()),
513 32 : peer_bgp_id_(0),
514 32 : peer_type_((config->peer_as() == config->local_as()) ?
515 : BgpProto::IBGP : BgpProto::EBGP),
516 32 : state_machine_(BgpStaticObjectFactory::Create<StateMachine>(this)),
517 32 : peer_close_(BgpStaticObjectFactory::Create<BgpPeerClose>(this)),
518 32 : peer_stats_(new PeerStats(this)),
519 32 : deleter_(new DeleteActor(this)),
520 32 : instance_delete_ref_(this, instance ? instance->deleter() : NULL),
521 32 : flap_count_(0),
522 32 : total_flap_count_(0),
523 32 : last_flap_(0),
524 32 : dscp_listener_id_(-1),
525 32 : inuse_authkey_type_(AuthenticationData::NIL),
526 32 : asn_listener_id_(-1),
527 640 : instance_op_(-1) {
528 32 : buffer_.reserve(buffer_capacity_);
529 32 : close_manager_.reset(
530 32 : BgpStaticObjectFactory::Create<PeerCloseManager>(static_cast<IPeerClose*>(peer_close_.get())));
531 32 : ostringstream oss1;
532 32 : oss1 << peer_key_.endpoint.address();
533 32 : if (peer_key_.endpoint.port() != BgpConfigManager::kDefaultPort)
534 32 : oss1 << ":" << dec << peer_key_.endpoint.port();
535 32 : to_str_ = oss1.str();
536 :
537 32 : ostringstream oss2;
538 32 : if (rtinstance_)
539 32 : oss2 << rtinstance_->name() << ":";
540 32 : oss2 << server_->localname() << ":";
541 32 : oss2 << peer_name();
542 32 : uve_key_str_ = oss2.str();
543 :
544 64 : if (router_type_ == "control-node" ||
545 32 : router_type_ == "external-control-node") {
546 0 : peer_is_control_node_ = true;
547 : } else {
548 32 : peer_is_control_node_ = false;
549 : }
550 :
551 32 : dscp_listener_id_ = server_->RegisterDSCPUpdateCallback(boost::bind(
552 : &BgpPeer::DSCPUpdateCallback, this, _1));
553 32 : if (IsRouterTypeBGPaaS()) {
554 0 : asn_listener_id_ = server->RegisterASNUpdateCallback(boost::bind(
555 : &BgpPeer::ASNUpdateCallback, this, _1, _2));
556 0 : instance_op_=server->routing_instance_mgr()->RegisterInstanceOpCallback(
557 : boost::bind(&BgpPeer::RoutingInstanceCallback, this, _1, _2));
558 : }
559 :
560 32 : membership_req_pending_ = 0;
561 32 : BGP_LOG_PEER(Event, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
562 : BGP_PEER_DIR_NA, "Created");
563 :
564 32 : if (rtinstance_ && peer_name_.find(rtinstance_->name()) == 0) {
565 32 : peer_basename_ = peer_name_.substr(rtinstance_->name().size() + 1);
566 : } else {
567 0 : peer_basename_ = peer_name_;
568 : }
569 :
570 32 : for (Address::Family family = Address::UNSPEC;
571 352 : family < Address::NUM_FAMILIES;
572 320 : family = static_cast<Address::Family>(family + 1)) {
573 320 : family_primary_path_count_[family] = 0;
574 640 : eor_send_timer_[family] =
575 960 : TimerManager::CreateTimer(*server->ioservice(),
576 640 : "BGP EoR Send timer for " + Address::FamilyToString(family),
577 : TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
578 : GetTaskInstance());
579 640 : eor_receive_timer_[family] =
580 960 : TimerManager::CreateTimer(*server->ioservice(),
581 640 : "BGP EoR Receive timer for " + Address::FamilyToString(family),
582 : TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
583 : GetTaskInstance());
584 : }
585 :
586 32 : total_path_count_ = 0;
587 32 : primary_path_count_ = 0;
588 :
589 : // Check rtinstance_ to accommodate unit tests.
590 32 : if (resolve_paths_ && rtinstance_) {
591 0 : rtinstance_->GetTable(Address::INET)->LocatePathResolver();
592 0 : rtinstance_->GetTable(Address::INET6)->LocatePathResolver();
593 : }
594 :
595 32 : ProcessEndpointConfig(config);
596 32 : ProcessAuthKeyChainConfig(config);
597 32 : ProcessFamilyAttributesConfig(config);
598 :
599 64 : BgpPeerInfoData peer_info;
600 32 : peer_info.set_name(ToUVEKey());
601 32 : peer_info.set_admin_down(admin_down_);
602 32 : peer_info.set_passive(passive_);
603 32 : peer_info.set_as_override(as_override_);
604 32 : peer_info.set_origin_override(origin_override_.origin_override);
605 32 : if (origin_override_.origin_override) {
606 0 : peer_info.set_route_origin(
607 0 : BgpAttr::OriginToString(origin_override_.origin));
608 : } else {
609 32 : peer_info.set_route_origin("-");
610 : }
611 32 : peer_info.set_router_type(router_type_);
612 32 : peer_info.set_cluster_id(Ip4Address(cluster_id_).to_string());
613 64 : peer_info.set_peer_type(
614 32 : PeerType() == BgpProto::IBGP ? "internal" : "external");
615 32 : peer_info.set_local_asn(local_as_);
616 32 : peer_info.set_peer_asn(peer_as_);
617 32 : peer_info.set_peer_port(peer_port_);
618 32 : peer_info.set_hold_time(hold_time_);
619 32 : peer_info.set_local_id(local_bgp_id_);
620 32 : peer_info.set_configured_families(configured_families_);
621 32 : peer_info.set_peer_address(peer_key_.endpoint.address().to_string());
622 32 : BGPPeerInfoSend(peer_info);
623 32 : }
624 :
625 32 : BgpPeer::~BgpPeer() {
626 32 : assert(!close_manager()->IsCloseInProgress());
627 32 : assert(!IsCloseInProgress());
628 32 : assert(GetTotalPathCount() == 0);
629 32 : STLDeleteValues(&family_attributes_list_);
630 32 : ClearListenSocketAuthKey();
631 64 : BgpPeerInfoData peer_info;
632 32 : peer_info.set_name(ToUVEKey());
633 32 : peer_info.set_deleted(true);
634 32 : BGPPeerInfoSend(peer_info);
635 :
636 64 : PeerStatsData peer_stats_data;
637 32 : peer_stats_data.set_name(ToUVEKey());
638 32 : peer_stats_data.set_deleted(true);
639 32 : assert(!peer_stats_data.get_name().empty());
640 32 : BGP_UVE_SEND2(PeerStatsUve, peer_stats_data, "ObjectBgpPeer");
641 :
642 64 : PeerFlapData peer_flap_data;
643 32 : peer_flap_data.set_name(ToUVEKey());
644 32 : peer_flap_data.set_deleted(true);
645 32 : assert(!peer_flap_data.get_name().empty());
646 32 : BGP_UVE_SEND2(PeerFlap, peer_flap_data, "ObjectBgpPeer");
647 :
648 32 : BGP_LOG_PEER(Event, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
649 : BGP_PEER_DIR_NA, "Deleted");
650 32 : }
651 :
652 32 : void BgpPeer::Initialize() {
653 32 : if (!admin_down_)
654 32 : state_machine_->Initialize();
655 32 : }
656 :
657 32 : size_t BgpPeer::GetBufferCapacity() const {
658 : // For testing only - configure through environment variable.
659 32 : char *buffer_capacity_str = getenv("BGP_PEER_BUFFER_SIZE");
660 32 : if (buffer_capacity_str) {
661 0 : size_t env_buffer_capacity = strtoul(buffer_capacity_str, NULL, 0);
662 0 : if (env_buffer_capacity < kMinBufferCapacity)
663 0 : env_buffer_capacity = kMinBufferCapacity;
664 0 : if (env_buffer_capacity > kMaxBufferCapacity)
665 0 : env_buffer_capacity = kMaxBufferCapacity;
666 0 : return env_buffer_capacity;
667 : }
668 :
669 : // Return internal default based on peer router-type.
670 32 : if (IsRouterTypeBGPaaS()) {
671 0 : return kMinBufferCapacity;
672 : } else {
673 32 : return kMaxBufferCapacity;
674 : }
675 : }
676 :
677 0 : bool BgpPeer::CheckSplitHorizon(uint32_t server_cluster_id,
678 : uint32_t ribout_cid) const {
679 0 : if (PeerType() == BgpProto::IBGP) {
680 : // check if router is a route reflector
681 0 : if (!server_cluster_id) return true;
682 : // check if received from client or non-client by comparing the clusterId
683 : // of router with that of peer from which we this route is received
684 0 : if (server_cluster_id != cluster_id_) {
685 : // If received from non-client, reflect to all the clients only
686 0 : if (ribout_cid && ribout_cid != server_cluster_id) {
687 0 : return true;
688 : }
689 : }
690 : }
691 0 : return false;
692 : }
693 :
694 0 : BgpTable *BgpPeer::GetRTargetTable() {
695 0 : RoutingInstanceMgr *instance_mgr = server_->routing_instance_mgr();
696 0 : if (!instance_mgr)
697 0 : return NULL;
698 0 : RoutingInstance *master = instance_mgr->GetDefaultRoutingInstance();
699 0 : if (!master)
700 0 : return NULL;
701 0 : return master->GetTable(Address::RTARGET);
702 : }
703 :
704 0 : BgpAttrPtr BgpPeer::GetRouteTargetRouteAttr() const {
705 0 : BgpAttrSpec attrs;
706 0 : BgpAttrNextHop nexthop(server_->bgp_identifier());
707 0 : attrs.push_back(&nexthop);
708 0 : BgpAttrOrigin origin(BgpAttrOrigin::IGP);
709 0 : attrs.push_back(&origin);
710 0 : return server_->attr_db()->Locate(attrs);
711 0 : }
712 :
713 : // Add one route-target route to bgp.rtarget.0 table.
714 0 : void BgpPeer::BGPaaSAddRTarget(as_t as, BgpTable *table, BgpAttrPtr attr,
715 : RouteTargetList::const_iterator it) {
716 0 : const RouteTarget rtarget = *it;
717 0 : DBRequest req;
718 0 : RTargetPrefix rt_prefix(as, rtarget);
719 0 : req.key.reset(new RTargetTable::RequestKey(rt_prefix, this));
720 0 : req.data.reset(new RTargetTable::RequestData(attr, 0, 0, 0, 0));
721 0 : req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
722 0 : table->Enqueue(&req);
723 0 : }
724 :
725 : // Add import route-targets of associated routing-instance in order to attract
726 : // the VN routes, if bgpaas session comes up within the instance.
727 0 : void BgpPeer::AddRTargets(as_t as) {
728 0 : if (!IsRouterTypeBGPaaS())
729 0 : return;
730 0 : assert(IsReady());
731 0 : BgpTable *table = GetRTargetTable();
732 0 : assert(table);
733 0 : BgpAttrPtr attr = GetRouteTargetRouteAttr();
734 0 : rtargets_ = rtinstance_->GetImportList();
735 0 : for (RouteTargetList::const_iterator it = rtargets_.begin();
736 0 : it != rtargets_.end(); it++) {
737 0 : BGPaaSAddRTarget(as, table, attr, it);
738 : }
739 0 : }
740 :
741 : // Delete one route-target route from bgp.rtarget.0 table.
742 0 : void BgpPeer::BGPaaSDeleteRTarget(as_t as, BgpTable *table,
743 : RouteTargetList::const_iterator it) {
744 0 : const RouteTarget rtarget = *it;
745 0 : DBRequest req;
746 0 : RTargetPrefix rt_prefix(as, rtarget);
747 0 : req.key.reset(new RTargetTable::RequestKey(rt_prefix, this));
748 0 : req.oper = DBRequest::DB_ENTRY_DELETE;
749 0 : table->Enqueue(&req);
750 0 : }
751 :
752 : // Delete import route-targets of associated routing-instance in order to
753 : // not to attract the VN routes any more, if bgpaas session goes down within
754 : // the instance.
755 80 : void BgpPeer::DeleteRTargets(as_t as) {
756 80 : if (!IsRouterTypeBGPaaS())
757 80 : return;
758 0 : BgpTable *table = GetRTargetTable();
759 0 : if (!table)
760 0 : return;
761 0 : for (RouteTargetList::const_iterator it = rtargets_.begin();
762 0 : it != rtargets_.end(); it++) {
763 0 : BGPaaSDeleteRTarget(as, table, it);
764 : }
765 0 : rtargets_.clear();
766 : }
767 :
768 0 : void BgpPeer::ASNUpdateCallback(as_t old_asn, as_t old_local_asn) {
769 0 : CHECK_CONCURRENCY("bgp::Config");
770 0 : DeleteRTargets(old_local_asn);
771 0 : if (!IsReady())
772 0 : return;
773 0 : AddRTargets(server_->local_autonomous_system());
774 : }
775 :
776 : // Process changes to routing-instance configuration. Specifically, we need
777 : // to track all import route-targets so that they can be correctly updated
778 : // when bgpaas sessions come up or go down.
779 0 : void BgpPeer::RoutingInstanceCallback(const std::string &vrf_name, int op) {
780 0 : assert(IsRouterTypeBGPaaS());
781 0 : if (op != RoutingInstanceMgr::INSTANCE_UPDATE || !IsReady())
782 0 : return;
783 0 : if (vrf_name != rtinstance_->name())
784 0 : return;
785 0 : RoutingInstanceMgr *instance_mgr = server_->routing_instance_mgr();
786 0 : RoutingInstance *master = instance_mgr->GetDefaultRoutingInstance();
787 0 : BgpTable *table = master->GetTable(Address::RTARGET);
788 0 : assert(table);
789 0 : BgpAttrPtr attr = GetRouteTargetRouteAttr();
790 0 : set_synchronize(&rtargets_, &rtinstance_->GetImportList(),
791 0 : boost::bind(&BgpPeer::BGPaaSAddRTarget, this,
792 0 : server_->local_autonomous_system(), table, attr, _1),
793 : boost::bind(&BgpPeer::BGPaaSDeleteRTarget, this,
794 0 : server_->local_autonomous_system(), table, _1));
795 0 : rtargets_ = rtinstance_->GetImportList();
796 0 : }
797 :
798 160 : void BgpPeer::NotifyEstablished(bool established) {
799 160 : if (established) {
800 80 : if (IsRouterTypeBGPaaS()) {
801 0 : server_->IncrementUpBgpaasPeerCount();
802 0 : AddRTargets(server_->local_autonomous_system());
803 : } else {
804 80 : server_->IncrementUpPeerCount();
805 : }
806 : } else {
807 80 : if (IsRouterTypeBGPaaS()) {
808 0 : server_->DecrementUpBgpaasPeerCount();
809 : } else {
810 80 : server_->DecrementUpPeerCount();
811 : }
812 : }
813 160 : }
814 :
815 0 : void BgpPeer::BindLocalEndpoint(BgpSession *session) {
816 0 : }
817 :
818 : // Just return the first entry for now.
819 0 : bool BgpPeer::GetBestAuthKey(AuthenticationKey *auth_key,
820 : KeyType *key_type) const {
821 0 : if (auth_data_.Empty()) {
822 0 : return false;
823 : }
824 0 : assert(auth_key);
825 0 : AuthenticationData::const_iterator iter = auth_data_.begin();
826 0 : *auth_key = *iter;
827 0 : *key_type = auth_data_.key_type();
828 0 : return true;
829 : }
830 :
831 64 : bool BgpPeer::ProcessAuthKeyChainConfig(const BgpNeighborConfig *config) {
832 64 : const AuthenticationData &input_auth_data = config->auth_data();
833 :
834 64 : if (auth_data_ == input_auth_data) {
835 64 : return false;
836 : }
837 :
838 0 : auth_data_ = input_auth_data;
839 0 : return InstallAuthKeys();
840 : }
841 :
842 0 : bool BgpPeer::InstallAuthKeys() {
843 0 : if (!PeerAddress()) {
844 0 : return false;
845 : }
846 :
847 0 : AuthenticationKey auth_key;
848 : KeyType key_type;
849 0 : bool valid = GetBestAuthKey(&auth_key, &key_type);
850 0 : if (valid) {
851 0 : if (key_type == AuthenticationData::MD5) {
852 0 : LogInstallAuthKeys("Listen", "add", auth_key, key_type);
853 0 : SetListenSocketAuthKey(auth_key, key_type);
854 0 : SetInuseAuthKeyInfo(auth_key, key_type);
855 : }
856 : } else {
857 : // If there are no valid available keys but an older one is currently
858 : // installed, un-install it.
859 0 : if (inuse_authkey_type_ == AuthenticationData::MD5) {
860 0 : LogInstallAuthKeys("Listen", "delete", inuse_auth_key_,
861 : inuse_authkey_type_);
862 0 : ClearListenSocketAuthKey();
863 : // Resetting the key information must be done last.
864 0 : ResetInuseAuthKeyInfo();
865 : }
866 : }
867 0 : return true;
868 0 : }
869 :
870 0 : void BgpPeer::SetInuseAuthKeyInfo(const AuthenticationKey &key, KeyType type) {
871 0 : inuse_auth_key_ = key;
872 0 : inuse_authkey_type_ = type;
873 0 : }
874 :
875 0 : void BgpPeer::ResetInuseAuthKeyInfo() {
876 0 : inuse_auth_key_.Reset();
877 0 : inuse_authkey_type_ = AuthenticationData::NIL;
878 0 : }
879 :
880 0 : void BgpPeer::SetListenSocketAuthKey(const AuthenticationKey &auth_key,
881 : KeyType key_type) {
882 0 : if (key_type == AuthenticationData::MD5) {
883 0 : server_->session_manager()->
884 0 : SetListenSocketMd5Option(PeerAddress(), auth_key.value);
885 : }
886 0 : }
887 :
888 32 : void BgpPeer::ClearListenSocketAuthKey() {
889 32 : if (inuse_authkey_type_ == AuthenticationData::MD5) {
890 0 : server_->session_manager()->SetListenSocketMd5Option(PeerAddress(), "");
891 : }
892 32 : }
893 :
894 208 : void BgpPeer::SetSessionSocketAuthKey(TcpSession *session) {
895 208 : if ((inuse_authkey_type_ == AuthenticationData::MD5) && PeerAddress()) {
896 0 : assert(!inuse_auth_key_.value.empty());
897 0 : LogInstallAuthKeys("Session", "add", inuse_auth_key_,
898 : inuse_authkey_type_);
899 0 : session->SetMd5SocketOption(PeerAddress(), inuse_auth_key_.value);
900 : }
901 208 : }
902 :
903 60 : void BgpPeer::SetSessionSocketOptionDscp(TcpSession *session) {
904 60 : uint8_t dscp_value = server_->global_qos()->control_dscp();
905 :
906 60 : if (!session->socket()) {
907 0 : return;
908 : }
909 60 : if (dscp_value != 0xFF) {
910 60 : session->SetDscpSocketOption(server_->global_qos()->control_dscp());
911 : }
912 : }
913 :
914 0 : string BgpPeer::GetInuseAuthKeyValue() const {
915 0 : return inuse_auth_key_.value;
916 : }
917 :
918 0 : void BgpPeer::LogInstallAuthKeys(const string &socket_name,
919 : const string &oper, const AuthenticationKey &auth_key,
920 : KeyType key_type) {
921 0 : string logstr = socket_name + " socket kernel " + oper + " of key id "
922 0 : + integerToString(auth_key.id) + ", type "
923 0 : + AuthenticationData::KeyTypeToString(key_type)
924 0 : + ", peer " + peer_name_;
925 0 : BGP_LOG_PEER(Config, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
926 : BGP_PEER_DIR_NA, logstr);
927 0 : }
928 :
929 : //
930 : // Check if the configured prefix limit for any address family has been
931 : // exceeded. If yes, clear the peer by sending a notification with a cease
932 : // subcode of MaxPrefixes.
933 : //
934 32 : bool BgpPeer::CheckPrefixLimits() {
935 32 : RetryDelete();
936 32 : if (!IsReady())
937 32 : return true;
938 0 : for (size_t idx = Address::UNSPEC; idx < Address::NUM_FAMILIES; ++idx) {
939 : BgpPeerFamilyAttributes *family_attributes =
940 0 : family_attributes_list_[idx];
941 0 : if (!family_attributes || family_attributes->prefix_limit == 0)
942 0 : continue;
943 0 : if (family_primary_path_count_[idx] <= family_attributes->prefix_limit)
944 0 : continue;
945 0 : Clear(BgpProto::Notification::MaxPrefixes);
946 0 : StartPrefixLimitIdleTimer(family_attributes->idle_timeout * 1000);
947 0 : break;
948 : }
949 0 : return true;
950 : }
951 :
952 : //
953 : // Process family attributes configuration and update the family attributes
954 : // list.
955 : //
956 : // Return true is there's a change, false otherwise.
957 : //
958 64 : bool BgpPeer::ProcessFamilyAttributesConfig(const BgpNeighborConfig *config) {
959 64 : FamilyAttributesList family_attributes_list(Address::NUM_FAMILIES);
960 704 : BOOST_FOREACH(const BgpFamilyAttributesConfig family_config,
961 : config->family_attributes_list()) {
962 : Address::Family family =
963 320 : Address::FamilyFromString(family_config.family);
964 320 : assert(family != Address::UNSPEC);
965 : BgpPeerFamilyAttributes *family_attributes =
966 320 : new BgpPeerFamilyAttributes(config, family_config);
967 320 : family_attributes_list[family] = family_attributes;
968 320 : }
969 :
970 64 : int ret = STLSortedCompare(
971 : family_attributes_list.begin(), family_attributes_list.end(),
972 : family_attributes_list_.begin(), family_attributes_list_.end(),
973 : BgpPeerFamilyAttributesCompare());
974 64 : STLDeleteValues(&family_attributes_list_);
975 64 : family_attributes_list_ = family_attributes_list;
976 64 : configured_families_ = config->GetAddressFamilies();
977 64 : return (ret != 0);
978 64 : }
979 :
980 64 : void BgpPeer::ProcessEndpointConfig(const BgpNeighborConfig *config) {
981 64 : if (config->router_type() == "bgpaas-client") {
982 0 : endpoint_ = TcpSession::Endpoint(Ip4Address(), config->source_port());
983 : } else {
984 64 : endpoint_ = TcpSession::Endpoint();
985 : }
986 64 : }
987 :
988 32 : void BgpPeer::TriggerPrefixLimitCheck() const {
989 32 : prefix_limit_trigger_.Set();
990 32 : }
991 :
992 32 : void BgpPeer::ConfigUpdate(const BgpNeighborConfig *config) {
993 32 : if (IsDeleted())
994 0 : return;
995 :
996 32 : config_ = config;
997 :
998 : // During peer deletion, configuration gets completely deleted. In that
999 : // case, there is no need to update the rest and flap the peer.
1000 32 : if (!config_)
1001 0 : return;
1002 :
1003 32 : bool clear_session = false;
1004 32 : bool admin_down_changed = false;
1005 64 : BgpPeerInfoData peer_info;
1006 32 : peer_info.set_name(ToUVEKey());
1007 :
1008 32 : if (admin_down_ != config->admin_down()) {
1009 0 : SetAdminState(config->admin_down());
1010 0 : peer_info.set_admin_down(admin_down_);
1011 0 : admin_down_changed = true;
1012 : }
1013 :
1014 32 : if (passive_ != config->passive()) {
1015 0 : passive_ = config->passive();
1016 0 : peer_info.set_passive(passive_);
1017 0 : clear_session = true;
1018 : }
1019 :
1020 32 : if (as_override_ != config->as_override()) {
1021 0 : as_override_ = config->as_override();
1022 0 : peer_info.set_as_override(as_override_);
1023 0 : clear_session = true;
1024 : }
1025 :
1026 32 : if (cluster_id_ != config->cluster_id()) {
1027 0 : cluster_id_ = config->cluster_id();
1028 0 : peer_info.set_cluster_id(Ip4Address(cluster_id_).to_string());
1029 0 : clear_session = true;
1030 : }
1031 :
1032 32 : OriginOverride origin_override(config->origin_override());
1033 32 : if (origin_override_ != origin_override) {
1034 0 : origin_override_ = origin_override;
1035 0 : peer_info.set_origin_override(origin_override_.origin_override);
1036 0 : if (origin_override_.origin_override) {
1037 0 : peer_info.set_route_origin(config->origin_override().origin);
1038 : } else {
1039 0 : peer_info.set_route_origin("-");
1040 : }
1041 0 : clear_session = true;
1042 : }
1043 :
1044 32 : if (router_type_ != config->router_type()) {
1045 0 : router_type_ = config->router_type();
1046 0 : peer_info.set_router_type(router_type_);
1047 0 : resolve_paths_ = (config->router_type() == "bgpaas-client");
1048 0 : clear_session = true;
1049 : }
1050 64 : if (router_type_ == "control-node" ||
1051 32 : router_type_ == "external-control-node") {
1052 0 : peer_is_control_node_ = true;
1053 : } else {
1054 32 : peer_is_control_node_ = false;
1055 : }
1056 :
1057 : // Check if there is any change in the peer address.
1058 : // If the peer address is changing, remove the key for the older address.
1059 : // Update with the new peer address and then process the key chain info
1060 : // for the new peer below.
1061 32 : BgpPeerKey key(config);
1062 32 : if (peer_key_ != key) {
1063 0 : ClearListenSocketAuthKey();
1064 0 : peer_key_ = key;
1065 0 : peer_info.set_peer_address(peer_key_.endpoint.address().to_string());
1066 0 : clear_session = true;
1067 : }
1068 32 : if (ProcessAuthKeyChainConfig(config)) {
1069 0 : clear_session = true;
1070 : }
1071 :
1072 32 : if (peer_port_ != config->source_port()) {
1073 0 : peer_port_ = config->source_port();
1074 0 : peer_info.set_peer_port(peer_port_);
1075 0 : clear_session = true;
1076 : }
1077 32 : ProcessEndpointConfig(config);
1078 :
1079 32 : if (local_as_ != config->local_as()) {
1080 0 : BGP_LOG_STR(BgpConfig, SandeshLevel::SYS_DEBUG,
1081 : BGP_LOG_FLAG_SYSLOG,
1082 : "Updated Local Autonomous System from " <<
1083 : local_as_ << " to " <<
1084 : config->local_as());
1085 :
1086 0 : local_as_ = config->local_as();
1087 0 : peer_info.set_local_asn(local_as_);
1088 0 : clear_session = true;
1089 : }
1090 :
1091 32 : if (hold_time_ != config->hold_time()) {
1092 0 : BGP_LOG_STR(BgpConfig, SandeshLevel::SYS_DEBUG,
1093 : BGP_LOG_FLAG_SYSLOG,
1094 : "Updated Hold Time from " <<
1095 : hold_time_ << " to " <<
1096 : config->hold_time());
1097 :
1098 0 : hold_time_ = config->hold_time();
1099 0 : peer_info.set_hold_time(hold_time_);
1100 0 : clear_session = true;
1101 : }
1102 :
1103 32 : if (peer_as_ != config->peer_as()) {
1104 0 : BGP_LOG_STR(BgpConfig, SandeshLevel::SYS_DEBUG,
1105 : BGP_LOG_FLAG_SYSLOG,
1106 : "Updated Peer Autonomous System from " <<
1107 : peer_as_ << " to " <<
1108 : config->peer_as());
1109 :
1110 0 : peer_as_ = config->peer_as();
1111 0 : peer_info.set_peer_asn(peer_as_);
1112 0 : clear_session = true;
1113 : }
1114 :
1115 32 : boost::system::error_code ec;
1116 32 : uint32_t local_bgp_id = config->local_identifier();
1117 32 : if (local_bgp_id_ != local_bgp_id) {
1118 0 : local_bgp_id_ = local_bgp_id;
1119 0 : peer_info.set_local_id(local_bgp_id_);
1120 0 : clear_session = true;
1121 : }
1122 :
1123 32 : BgpProto::BgpPeerType old_type = PeerType();
1124 32 : peer_type_ = (peer_as_ == local_as_) ? BgpProto::IBGP : BgpProto::EBGP;
1125 32 : if (old_type != PeerType()) {
1126 0 : peer_info.set_peer_type(
1127 0 : PeerType() == BgpProto::IBGP ? "internal" : "external");
1128 0 : clear_session = true;
1129 : }
1130 :
1131 : // Check if there is any change in private-as-action configuration.
1132 32 : if (private_as_action_ != config->private_as_action()) {
1133 0 : private_as_action_ = config->private_as_action();
1134 0 : clear_session = true;
1135 : }
1136 :
1137 : // Check if there is any change in the configured address families.
1138 32 : if (ProcessFamilyAttributesConfig(config)) {
1139 0 : peer_info.set_configured_families(configured_families_);
1140 0 : clear_session = true;
1141 : } else {
1142 32 : TriggerPrefixLimitCheck();
1143 : }
1144 :
1145 : // Note that the state machine would have been stopped via SetAdminDown
1146 : // if admin down was set to true above. Further, it's not necessary to
1147 : // clear the peer if it's already admin down.
1148 32 : if (!admin_down_changed && !admin_down_ && clear_session) {
1149 0 : BGP_LOG_PEER(Config, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
1150 : BGP_PEER_DIR_NA,
1151 : "Session cleared due to configuration change");
1152 0 : Clear(BgpProto::Notification::OtherConfigChange);
1153 : }
1154 :
1155 : // Send the UVE as appropriate.
1156 32 : if (admin_down_changed || clear_session) {
1157 0 : StopPrefixLimitIdleTimer();
1158 0 : BGPPeerInfoSend(peer_info);
1159 : }
1160 32 : }
1161 :
1162 0 : void BgpPeer::ClearConfig() {
1163 0 : CHECK_CONCURRENCY("bgp::Config");
1164 0 : config_ = NULL;
1165 0 : }
1166 :
1167 148 : LifetimeActor *BgpPeer::deleter() {
1168 148 : return deleter_.get();
1169 : }
1170 :
1171 : //
1172 : // Check if the given address family has been negotiated with the peer.
1173 : //
1174 29248 : bool BgpPeer::IsFamilyNegotiated(Address::Family family) {
1175 : // Bail if the family is not configured locally.
1176 29248 : if (!LookupFamily(family))
1177 384 : return false;
1178 :
1179 : // Check if the peer advertised it in his Open message.
1180 : uint16_t afi;
1181 : uint8_t safi;
1182 28862 : tie(afi, safi) = BgpAf::FamilyToAfiSafi(family);
1183 28857 : return MpNlriAllowed(afi, safi);
1184 : }
1185 :
1186 : // Release resources for a peer that is going to be deleted.
1187 32 : void BgpPeer::PostCloseRelease() {
1188 32 : if (index_ != -1) {
1189 32 : server_->UnregisterPeer(this);
1190 32 : index_ = -1;
1191 : }
1192 32 : TimerManager::DeleteTimer(keepalive_timer_);
1193 32 : TimerManager::DeleteTimer(prefix_limit_idle_timer_);
1194 :
1195 32 : for (Address::Family family = Address::UNSPEC;
1196 352 : family < Address::NUM_FAMILIES;
1197 320 : family = static_cast<Address::Family>(family + 1)) {
1198 320 : TimerManager::DeleteTimer(eor_send_timer_[family]);
1199 320 : TimerManager::DeleteTimer(eor_receive_timer_[family]);
1200 : }
1201 32 : }
1202 :
1203 : // IsReady
1204 : //
1205 : // Check whether this peer is up and ready
1206 : //
1207 50561 : bool BgpPeer::IsReady() const {
1208 50561 : return state_machine_->get_state() == StateMachine::ESTABLISHED;
1209 : }
1210 :
1211 34299 : bool BgpPeer::IsXmppPeer() const {
1212 34299 : return false;
1213 : }
1214 :
1215 0 : uint32_t BgpPeer::local_bgp_identifier() const {
1216 0 : return ntohl(local_bgp_id_);
1217 : }
1218 :
1219 0 : string BgpPeer::local_bgp_identifier_string() const {
1220 0 : return Ip4Address(ntohl(local_bgp_id_)).to_string();
1221 : }
1222 :
1223 32 : uint32_t BgpPeer::bgp_identifier() const {
1224 32 : return ntohl(peer_bgp_id_);
1225 : }
1226 :
1227 0 : string BgpPeer::bgp_identifier_string() const {
1228 0 : return Ip4Address(ntohl(peer_bgp_id_)).to_string();
1229 : }
1230 :
1231 0 : string BgpPeer::transport_address_string() const {
1232 0 : TcpSession::Endpoint endpoint;
1233 0 : ostringstream oss;
1234 0 : if (session_)
1235 0 : endpoint = session_->remote_endpoint();
1236 0 : oss << endpoint;
1237 0 : return oss.str();
1238 0 : }
1239 :
1240 0 : string BgpPeer::gateway_address_string(Address::Family family) const {
1241 0 : if (!family_attributes_list_[family])
1242 0 : return string();
1243 0 : return family_attributes_list_[family]->gateway_address.to_string();
1244 : }
1245 :
1246 : //
1247 : // Customized close routing for BgpPeers.
1248 : //
1249 : // Reset all stored capabilities information and cancel outstanding timers.
1250 : //
1251 168 : void BgpPeer::CustomClose() {
1252 168 : ResetCapabilities();
1253 168 : keepalive_timer_->Cancel();
1254 :
1255 168 : for (Address::Family family = Address::UNSPEC;
1256 1848 : family < Address::NUM_FAMILIES;
1257 1680 : family = static_cast<Address::Family>(family + 1)) {
1258 1680 : eor_send_timer_[family]->Cancel();
1259 1680 : eor_receive_timer_[family]->Cancel();
1260 : }
1261 :
1262 168 : if (close_manager_->IsInDeleteState())
1263 80 : DeleteRTargets(server_->local_autonomous_system());
1264 168 : }
1265 :
1266 : //
1267 : // Close this peer by closing all of it's RIBs.
1268 : //
1269 184 : void BgpPeer::Close(bool graceful) {
1270 184 : send_ready_ = true;
1271 184 : if (membership_req_pending_ && !close_manager_->IsMembershipInUse()) {
1272 16 : BGP_LOG_PEER(Event, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
1273 : BGP_PEER_DIR_NA, "Close procedure deferred");
1274 16 : defer_close_ = true;
1275 :
1276 : // Note down non-graceful closures. Once a close is non-graceful,
1277 : // it shall remain as non-graceful.
1278 16 : graceful_close_ &= graceful;
1279 16 : return;
1280 : }
1281 :
1282 168 : peer_close_->Close(graceful);
1283 : }
1284 :
1285 0 : IPeerClose *BgpPeer::peer_close() {
1286 0 : return peer_close_.get();
1287 : }
1288 :
1289 8533 : IPeerClose *BgpPeer::peer_close() const {
1290 8533 : return peer_close_.get();
1291 : }
1292 :
1293 8533 : void BgpPeer::UpdateCloseRouteStats(Address::Family family,
1294 : const BgpPath *old_path, uint32_t path_flags) const {
1295 8533 : peer_close()->UpdateRouteStats(family, old_path, path_flags);
1296 8533 : }
1297 :
1298 10471 : IPeerDebugStats *BgpPeer::peer_stats() {
1299 10471 : return peer_stats_.get();
1300 : }
1301 :
1302 0 : const IPeerDebugStats *BgpPeer::peer_stats() const {
1303 0 : return peer_stats_.get();
1304 : }
1305 :
1306 48 : void BgpPeer::Clear(int subcode) {
1307 48 : CHECK_CONCURRENCY("bgp::Config", "bgp::StateMachine");
1308 48 : state_machine_->Shutdown(subcode);
1309 48 : }
1310 :
1311 : //
1312 : // Check whether this peer has been marked for deletion from configuration
1313 : //
1314 808 : bool BgpPeer::IsDeleted() const {
1315 808 : return deleter_->IsDeleted();
1316 : }
1317 :
1318 99 : bool BgpPeer::IsInGRTimerWaitState() const {
1319 99 : return close_manager_->IsInGRTimerWaitState();
1320 : }
1321 :
1322 260 : bool BgpPeer::IsCloseInProgress() const {
1323 260 : CHECK_CONCURRENCY("bgp::Config", "bgp::StateMachine");
1324 :
1325 : // trigger is set only after defer_close is reset
1326 260 : assert(!(defer_close_ && trigger_.IsSet()));
1327 555 : return defer_close_ || trigger_.IsSet() ||
1328 260 : (close_manager_->IsCloseInProgress() &&
1329 295 : !IsInGRTimerWaitState());
1330 : }
1331 :
1332 16 : StateMachine::State BgpPeer::GetState() const {
1333 16 : return state_machine_->get_state();
1334 : }
1335 :
1336 0 : const string BgpPeer::GetStateName() const {
1337 0 : return state_machine_->StateName();
1338 : }
1339 :
1340 148 : BgpSession *BgpPeer::CreateSession() {
1341 148 : if (PrefixLimitIdleTimerRunning())
1342 0 : return NULL;
1343 :
1344 148 : TcpSession *session = server_->session_manager()->CreateSession();
1345 148 : if (session == NULL)
1346 0 : return NULL;
1347 :
1348 : // Set valid keys, if any, in the socket.
1349 148 : SetSessionSocketAuthKey(session);
1350 :
1351 148 : BgpSession *bgp_session = static_cast<BgpSession *>(session);
1352 148 : BindLocalEndpoint(bgp_session);
1353 148 : bgp_session->set_peer(this);
1354 148 : return bgp_session;
1355 : }
1356 :
1357 32 : void BgpPeer::SetAdminState(bool down, int subcode) {
1358 32 : CHECK_CONCURRENCY("bgp::Config");
1359 32 : if (admin_down_ == down)
1360 0 : return;
1361 32 : admin_down_ = down;
1362 32 : state_machine_->SetAdminState(down, subcode);
1363 32 : if (admin_down_) {
1364 16 : BGP_LOG_PEER(Config, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
1365 : BGP_PEER_DIR_NA, "Session cleared due to admin down");
1366 : }
1367 : }
1368 :
1369 60 : bool BgpPeer::AcceptSession(BgpSession *session) {
1370 60 : session->set_peer(this);
1371 :
1372 : // Set valid keys, if any, in the socket.
1373 60 : SetSessionSocketAuthKey(session);
1374 :
1375 : // Set control dscp, if any
1376 60 : SetSessionSocketOptionDscp(session);
1377 :
1378 60 : return state_machine_->PassiveOpen(session);
1379 : }
1380 :
1381 344 : void BgpPeer::Register(BgpTable *table, const RibExportPolicy &policy) {
1382 : // In a highly corner case scenario, GR timer could fire right after a
1383 : // session comes back up. In that case, CloseManager possibly could still
1384 : // be using membership manager. Instead of creating a queue of these
1385 : // register requests until close manager is done processing and process
1386 : // them later, we could just as well just reset the session.
1387 344 : if (close_manager_->IsMembershipInUse()) {
1388 0 : BGP_LOG_PEER(Config, this, SandeshLevel::SYS_NOTICE, BGP_LOG_FLAG_ALL,
1389 : BGP_PEER_DIR_IN, "Session cleared due to GR not ready");
1390 0 : Close(true);
1391 : }
1392 :
1393 344 : if (close_manager_->IsMembershipInWait())
1394 0 : assert(membership_req_pending_ > 0);
1395 344 : BgpMembershipManager *membership_mgr = server_->membership_mgr();
1396 344 : membership_req_pending_++;
1397 344 : membership_mgr->Register(this, table, policy);
1398 :
1399 : // Start EndOfRib receive timer.
1400 344 : StartEndOfRibReceiveTimer(table->family());
1401 344 : }
1402 :
1403 320 : void BgpPeer::Register(BgpTable *table) {
1404 320 : if (close_manager_->IsMembershipInUse()) {
1405 0 : BGP_LOG_PEER(Config, this, SandeshLevel::SYS_NOTICE, BGP_LOG_FLAG_ALL,
1406 : BGP_PEER_DIR_IN, "Session cleared due to GR not ready");
1407 0 : Close(true);
1408 : }
1409 :
1410 320 : if (close_manager_->IsMembershipInWait())
1411 0 : assert(membership_req_pending_ > 0);
1412 320 : BgpMembershipManager *membership_mgr = server_->membership_mgr();
1413 320 : membership_mgr->RegisterRibIn(this, table);
1414 :
1415 : // Start EndOfRib receive timer.
1416 320 : StartEndOfRibReceiveTimer(table->family());
1417 320 : }
1418 :
1419 : //
1420 : // Register to tables for negotiated address families.
1421 : //
1422 : // If the route-target family is negotiated, defer ribout registration
1423 : // to VPN tables till we receive End-Of-RIB marker for the route-target
1424 : // NLRI or till the EndOfRibTimer expires. This ensures that we do not
1425 : // start sending VPN routes to the peer till we know what route targets
1426 : // the peer is interested in.
1427 : //
1428 : // Note that we do ribin registration right away even if the route-target
1429 : // family is negotiated. This allows received VPN routes to be processed
1430 : // normally before ribout registration to VPN tables is completed.
1431 : //
1432 80 : void BgpPeer::RegisterAllTables() {
1433 80 : RoutingInstance *instance = GetRoutingInstance();
1434 :
1435 80 : BGP_LOG_PEER(Event, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
1436 : BGP_PEER_DIR_NA, "Established");
1437 :
1438 : vector<Address::Family> family_list = list_of
1439 80 : (Address::INET)(Address::INETMPLS)(Address::INET6);
1440 554 : BOOST_FOREACH(Address::Family family, family_list) {
1441 237 : if (!IsFamilyNegotiated(family))
1442 238 : continue;
1443 0 : BgpTable *table = instance->GetTable(family);
1444 0 : BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_TRACE,
1445 : table, "Register peer with the table");
1446 0 : Register(table, BuildRibExportPolicy(family));
1447 : }
1448 :
1449 :
1450 160 : if (((router_type_ == "bgpaas-client") ||
1451 160 : (router_type_ == "bgpaas-server")) &&
1452 0 : (instance->routing_instance_vxlan() != "")) {
1453 0 : RoutingInstanceMgr *mgr = server()->routing_instance_mgr();
1454 0 : if (mgr != nullptr) {
1455 : RoutingInstance *vxlan_ri =
1456 0 : mgr->GetRoutingInstance(instance->routing_instance_vxlan());
1457 0 : if (vxlan_ri != nullptr) {
1458 0 : BgpTable *table = vxlan_ri->GetTable(Address::EVPN);
1459 0 : BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_TRACE,
1460 : table, "Register ribin for peer with the table");
1461 0 : Register(table);
1462 : }
1463 : }
1464 : }
1465 :
1466 80 : vpn_tables_registered_ = false;
1467 80 : if (!IsFamilyNegotiated(Address::RTARGET)) {
1468 0 : RegisterToVpnTables();
1469 0 : return;
1470 : }
1471 :
1472 80 : Address::Family family = Address::RTARGET;
1473 80 : BgpTable *table = instance->GetTable(family);
1474 120 : BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_TRACE,
1475 : table, "Register peer with the table");
1476 80 : Register(table, BuildRibExportPolicy(family));
1477 :
1478 : vector<Address::Family> vpn_family_list = list_of
1479 80 : (Address::INETVPN)(Address::INET6VPN)(Address::ERMVPN)(Address::EVPN)
1480 80 : (Address::MVPN);
1481 880 : BOOST_FOREACH(Address::Family vpn_family, vpn_family_list) {
1482 400 : if (!IsFamilyNegotiated(vpn_family))
1483 80 : continue;
1484 320 : BgpTable *table = instance->GetTable(vpn_family);
1485 480 : BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_TRACE,
1486 : table, "Register ribin for peer with the table");
1487 320 : Register(table);
1488 : }
1489 80 : }
1490 :
1491 : const vector<Address::Family> BgpPeer::supported_families_ = list_of
1492 : (Address::INET)
1493 : (Address::INETMPLS)
1494 : (Address::INETVPN)
1495 : (Address::EVPN)
1496 : (Address::RTARGET)
1497 : (Address::ERMVPN)
1498 : (Address::MVPN)
1499 : (Address::INET6)
1500 : (Address::INET6VPN);
1501 :
1502 188 : void BgpPeer::SendOpen(TcpSession *session) {
1503 188 : BgpProto::OpenMessage openmsg;
1504 188 : openmsg.as_num = local_as_ > 0xffff ? AS_TRANS : local_as_;
1505 188 : openmsg.holdtime = state_machine_->GetConfiguredHoldTime();
1506 188 : openmsg.identifier = ntohl(local_bgp_id_);
1507 : BgpProto::OpenMessage::OptParam *opt_param =
1508 188 : new BgpProto::OpenMessage::OptParam;
1509 :
1510 : static const uint8_t cap_mp[][4] = {
1511 1 : { 0, (uint8_t) BgpAf::FamilyToAfi(supported_families_[0]), 0,
1512 1 : BgpAf::FamilyToSafi(supported_families_[0]) },
1513 1 : { 0, (uint8_t) BgpAf::FamilyToAfi(supported_families_[1]), 0,
1514 1 : BgpAf::FamilyToSafi(supported_families_[1]) },
1515 1 : { 0, (uint8_t) BgpAf::FamilyToAfi(supported_families_[2]), 0,
1516 1 : BgpAf::FamilyToSafi(supported_families_[2]) },
1517 1 : { 0, (uint8_t) BgpAf::FamilyToAfi(supported_families_[3]), 0,
1518 1 : BgpAf::FamilyToSafi(supported_families_[3]) },
1519 1 : { 0, (uint8_t) BgpAf::FamilyToAfi(supported_families_[4]), 0,
1520 1 : BgpAf::FamilyToSafi(supported_families_[4]) },
1521 1 : { 0, (uint8_t) BgpAf::FamilyToAfi(supported_families_[5]), 0,
1522 1 : BgpAf::FamilyToSafi(supported_families_[5]) },
1523 1 : { 0, (uint8_t) BgpAf::FamilyToAfi(supported_families_[6]), 0,
1524 1 : BgpAf::FamilyToSafi(supported_families_[6]) },
1525 1 : { 0, (uint8_t) BgpAf::FamilyToAfi(supported_families_[7]), 0,
1526 1 : BgpAf::FamilyToSafi(supported_families_[7]) },
1527 1 : { 0, (uint8_t) BgpAf::FamilyToAfi(supported_families_[8]), 0,
1528 1 : BgpAf::FamilyToSafi(supported_families_[8]) },
1529 206 : };
1530 :
1531 : static const FamilyToCapabilityMap family_to_cap_map = map_list_of
1532 2 : (supported_families_[0], cap_mp[0])
1533 1 : (supported_families_[1], cap_mp[1])
1534 1 : (supported_families_[2], cap_mp[2])
1535 1 : (supported_families_[3], cap_mp[3])
1536 1 : (supported_families_[4], cap_mp[4])
1537 1 : (supported_families_[5], cap_mp[5])
1538 1 : (supported_families_[6], cap_mp[6])
1539 1 : (supported_families_[7], cap_mp[7])
1540 189 : (supported_families_[8], cap_mp[8]);
1541 :
1542 : // Add capabilities for configured address families.
1543 3572 : BOOST_FOREACH(const FamilyToCapabilityMap::value_type &val,
1544 : family_to_cap_map) {
1545 1692 : if (!LookupFamily(val.first))
1546 752 : continue;
1547 : BgpProto::OpenMessage::Capability *cap =
1548 : new BgpProto::OpenMessage::Capability(
1549 940 : BgpProto::OpenMessage::Capability::MpExtension, val.second, 4);
1550 940 : opt_param->capabilities.push_back(cap);
1551 : }
1552 :
1553 188 : if (server_->enable_4byte_as()) {
1554 0 : uint32_t asn = ntohl(local_as_);
1555 : BgpProto::OpenMessage::Capability *cap =
1556 : new BgpProto::OpenMessage::Capability(
1557 : BgpProto::OpenMessage::Capability::AS4Support,
1558 0 : (const uint8_t *)(&asn), 4);
1559 0 : opt_param->capabilities.push_back(cap);
1560 : }
1561 188 : peer_close_->AddGRCapabilities(opt_param);
1562 188 : peer_close_->AddLLGRCapabilities(opt_param);
1563 :
1564 188 : if (opt_param->capabilities.size()) {
1565 188 : openmsg.opt_params.push_back(opt_param);
1566 : } else {
1567 0 : delete opt_param;
1568 : }
1569 : uint8_t data[256];
1570 188 : int result = BgpProto::Encode(&openmsg, data, sizeof(data));
1571 188 : assert(result > BgpProto::kMinMessageSize);
1572 188 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
1573 : BGP_PEER_DIR_OUT, "Open " << openmsg.ToString());
1574 188 : session->Send(data, result, NULL);
1575 188 : inc_tx_open();
1576 188 : }
1577 :
1578 80 : void BgpPeer::SendKeepalive(bool from_timer) {
1579 80 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
1580 :
1581 : // Bail if there's no session for the peer anymore.
1582 80 : if (!session_)
1583 0 : return;
1584 :
1585 80 : BgpProto::Keepalive msg;
1586 : uint8_t data[BgpProto::kMinMessageSize];
1587 80 : int result = BgpProto::Encode(&msg, data, sizeof(data));
1588 80 : assert(result == BgpProto::kMinMessageSize);
1589 80 : SandeshLevel::type log_level = from_timer ? Sandesh::LoggingUtLevel() :
1590 80 : SandeshLevel::SYS_INFO;
1591 80 : BGP_LOG_PEER(Message, this, log_level, BGP_LOG_FLAG_SYSLOG,
1592 : BGP_PEER_DIR_OUT, "Keepalive");
1593 80 : send_ready_ = session_->Send(data, result, NULL);
1594 80 : inc_tx_keepalive();
1595 80 : }
1596 :
1597 8266 : static bool SkipUpdateSend() {
1598 : static bool init_;
1599 : static bool skip_;
1600 :
1601 8266 : if (init_) return skip_;
1602 :
1603 1 : skip_ = getenv("BGP_SKIP_UPDATE_SEND") != NULL;
1604 1 : init_ = true;
1605 :
1606 1 : return skip_;
1607 : }
1608 :
1609 64 : BgpPeer::OriginOverride::OriginOverride(
1610 64 : const BgpNeighborConfig::OriginOverrideConfig &config)
1611 64 : : origin_override(config.origin_override),
1612 64 : origin(BgpAttr::OriginFromString(config.origin)) {
1613 64 : }
1614 :
1615 32 : bool BgpPeer::OriginOverride::operator!=(const OriginOverride &rhs) const {
1616 32 : if (origin_override != rhs.origin_override) {
1617 0 : return true;
1618 : }
1619 :
1620 : // compare origin only if override is set
1621 32 : if (origin_override && origin != rhs.origin) {
1622 0 : return true;
1623 : }
1624 32 : return false;
1625 : }
1626 :
1627 : //
1628 : // Accumulate the message in the update buffer.
1629 : // Flush the existing buffer if the message can't fit.
1630 : // Note that FlushUpdateUnlocked clears the buffer.
1631 : //
1632 10391 : bool BgpPeer::SendUpdate(const uint8_t *msg, size_t msgsize,
1633 : const string *msg_str) {
1634 10391 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
1635 10391 : bool send_ready = true;
1636 10391 : if (buffer_.size() + msgsize > buffer_capacity_) {
1637 0 : send_ready = FlushUpdateUnlocked();
1638 0 : assert(buffer_.empty());
1639 : }
1640 10391 : buffer_.insert(buffer_.end(), msg, msg + msgsize);
1641 10390 : inc_tx_update();
1642 10391 : return send_ready;
1643 10390 : }
1644 :
1645 9839 : bool BgpPeer::FlushUpdateUnlocked() {
1646 : // Bail if the update buffer is empty.
1647 9839 : if (buffer_.empty())
1648 501 : return true;
1649 :
1650 : // Bail if there's no session for the peer anymore.
1651 9338 : if (!session_) {
1652 1072 : buffer_.clear();
1653 1072 : return true;
1654 : }
1655 :
1656 8266 : if (!SkipUpdateSend()) {
1657 8266 : send_ready_ = session_->Send(buffer_.data(), buffer_.size(), NULL);
1658 8265 : buffer_.clear();
1659 8265 : if (send_ready_) {
1660 8265 : StartKeepaliveTimerUnlocked();
1661 : } else {
1662 0 : StopKeepaliveTimerUnlocked();
1663 : }
1664 : } else {
1665 0 : send_ready_ = true;
1666 : }
1667 :
1668 8266 : if (!send_ready_) {
1669 0 : BGP_LOG_PEER(Event, this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_ALL,
1670 : BGP_PEER_DIR_NA, "Send blocked");
1671 : }
1672 8266 : return send_ready_;
1673 : }
1674 :
1675 9830 : bool BgpPeer::FlushUpdate() {
1676 9830 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
1677 19678 : return FlushUpdateUnlocked();
1678 9839 : }
1679 :
1680 48 : bool BgpPeer::notification() const {
1681 48 : return peer_close_->gr_params().notification();
1682 : }
1683 :
1684 : // Check if GR Helper mode sould be attempted.
1685 184 : bool BgpPeer::AttemptGRHelperMode(int code, int subcode) const {
1686 184 : if (!code)
1687 88 : return true;
1688 :
1689 96 : if (code == BgpProto::Notification::Cease &&
1690 96 : (subcode == BgpProto::Notification::HardReset ||
1691 : subcode == BgpProto::Notification::PeerDeconfigured)) {
1692 48 : return false;
1693 : }
1694 :
1695 : // If Peer supports Notification (N) bit, then attempt GR-Helper for all
1696 : // other notifications, not otherwise.
1697 48 : return notification();
1698 : }
1699 :
1700 86 : void BgpPeer::SendNotification(BgpSession *session,
1701 : int code, int subcode, const string &data) {
1702 86 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
1703 86 : session->SendNotification(code, subcode, data);
1704 86 : state_machine_->set_last_notification_out(code, subcode, data);
1705 86 : inc_tx_notification();
1706 86 : }
1707 :
1708 80 : bool BgpPeer::SetCapabilities(const BgpProto::OpenMessage *msg) {
1709 80 : peer_bgp_id_ = htonl(msg->identifier);
1710 80 : capabilities_.clear();
1711 80 : vector<BgpProto::OpenMessage::OptParam *>::const_iterator it;
1712 160 : for (it = msg->opt_params.begin(); it < msg->opt_params.end(); ++it) {
1713 80 : capabilities_.insert(capabilities_.end(), (*it)->capabilities.begin(),
1714 80 : (*it)->capabilities.end());
1715 80 : (*it)->capabilities.clear();
1716 : }
1717 :
1718 80 : as4_supported_ = false;
1719 80 : if (server_->enable_4byte_as()) {
1720 0 : vector<BgpProto::OpenMessage::Capability *>::iterator c_it;
1721 0 : for (c_it = capabilities_.begin(); c_it < capabilities_.end(); ++c_it) {
1722 0 : if ((*c_it)->code ==BgpProto::OpenMessage::Capability::AS4Support) {
1723 0 : as4_supported_ = true;
1724 0 : break;
1725 : }
1726 : }
1727 : }
1728 160 : BgpPeerInfoData peer_info;
1729 80 : peer_info.set_name(ToUVEKey());
1730 80 : peer_info.set_peer_id(peer_bgp_id_);
1731 :
1732 80 : vector<string> families;
1733 80 : vector<BgpProto::OpenMessage::Capability *>::iterator cap_it;
1734 624 : for (cap_it = capabilities_.begin(); cap_it < capabilities_.end();
1735 544 : ++cap_it) {
1736 544 : if ((*cap_it)->code != BgpProto::OpenMessage::Capability::MpExtension)
1737 144 : continue;
1738 400 : uint8_t *data = (*cap_it)->capability.data();
1739 400 : uint16_t afi = get_value(data, 2);
1740 400 : uint8_t safi = get_value(data + 3, 1);
1741 400 : Address::Family family = BgpAf::AfiSafiToFamily(afi, safi);
1742 400 : if (family == Address::UNSPEC) {
1743 0 : families.push_back(BgpAf::ToString(afi, safi));
1744 : } else {
1745 400 : families.push_back(Address::FamilyToString(family));
1746 : }
1747 : }
1748 80 : peer_info.set_families(families);
1749 :
1750 80 : negotiated_families_.clear();
1751 879 : for (int idx = Address::UNSPEC; idx < Address::NUM_FAMILIES; ++idx) {
1752 799 : if (!family_attributes_list_[idx])
1753 400 : continue;
1754 399 : Address::Family family = static_cast<Address::Family>(idx);
1755 : uint16_t afi;
1756 : uint8_t safi;
1757 399 : tie(afi, safi) = BgpAf::FamilyToAfiSafi(family);
1758 400 : if (!MpNlriAllowed(afi, safi))
1759 0 : continue;
1760 400 : negotiated_families_.push_back(Address::FamilyToString(family));
1761 : }
1762 80 : sort(negotiated_families_.begin(), negotiated_families_.end());
1763 80 : peer_info.set_negotiated_families(negotiated_families_);
1764 :
1765 : // Process GR/LLGR capabilities and close non-gracefully if any ongoing GR
1766 : // needs be aborted.
1767 80 : if (!peer_close_->SetGRCapabilities(&peer_info)) {
1768 0 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
1769 : BGP_PEER_DIR_IN, "Close non-gracefully");
1770 0 : Close(false);
1771 0 : return false;
1772 : }
1773 80 : return true;
1774 80 : }
1775 :
1776 : // Reset capabilities stored inside peer structure.
1777 : //
1778 : // When open message is processed, we directly take the capabilities off the
1779 : // open message and store inside the peer structure.
1780 : //
1781 168 : void BgpPeer::ResetCapabilities() {
1782 168 : STLDeleteValues(&capabilities_);
1783 336 : BgpPeerInfoData peer_info;
1784 168 : peer_info.set_name(ToUVEKey());
1785 168 : vector<string> families = vector<string>();
1786 168 : peer_info.set_families(families);
1787 168 : vector<string> negotiated_families = vector<string>();
1788 168 : peer_info.set_negotiated_families(negotiated_families);
1789 168 : peer_info.set_graceful_restart_families(vector<string>());
1790 168 : BGPPeerInfoSend(peer_info);
1791 168 : }
1792 :
1793 29258 : bool BgpPeer::MpNlriAllowed(uint16_t afi, uint8_t safi) {
1794 29258 : vector<BgpProto::OpenMessage::Capability *>::iterator it;
1795 78368 : for (it = capabilities_.begin(); it < capabilities_.end(); ++it) {
1796 78366 : if ((*it)->code != BgpProto::OpenMessage::Capability::MpExtension)
1797 0 : continue;
1798 78368 : uint8_t *data = (*it)->capability.data();
1799 78363 : uint16_t af_value = get_value(data, 2);
1800 78366 : uint8_t safi_value = get_value(data + 3, 1);
1801 78367 : if (afi == af_value && safi == safi_value) {
1802 29257 : return true;
1803 : }
1804 : }
1805 0 : return false;
1806 : }
1807 :
1808 10197 : bool BgpPeer::Is4ByteAsSupported() const {
1809 10197 : return as4_supported_;
1810 : }
1811 :
1812 : template <typename TableT, typename PrefixT>
1813 9182 : void BgpPeer::ProcessNlri(Address::Family family, DBRequest::DBOperation oper,
1814 : const BgpMpNlri *nlri, BgpAttrPtr attr, uint32_t flags) {
1815 9182 : TableT *table = static_cast<TableT *>(rtinstance_->GetTable(family));
1816 9182 : assert(table);
1817 :
1818 20797 : for (vector<BgpProtoPrefix *>::const_iterator it = nlri->nlri.begin();
1819 20797 : it != nlri->nlri.end(); ++it) {
1820 11615 : PrefixT prefix;
1821 11615 : BgpAttrPtr new_attr(attr);
1822 11615 : uint32_t label = 0;
1823 11615 : uint32_t l3_label = 0;
1824 19794 : int result = PrefixT::FromProtoPrefix(server_, **it,
1825 8179 : (oper == DBRequest::DB_ENTRY_ADD_CHANGE ? attr.get() : NULL),
1826 : family, &prefix, &new_attr, &label, &l3_label);
1827 11615 : if (result) {
1828 0 : BGP_LOG_PEER_WARNING(Message, this,
1829 : BGP_LOG_FLAG_ALL, BGP_PEER_DIR_IN,
1830 : "MP NLRI parse error for " <<
1831 : Address::FamilyToString(family) << " route");
1832 0 : continue;
1833 0 : }
1834 :
1835 11615 : DBRequest req;
1836 11615 : req.oper = oper;
1837 11615 : if (oper == DBRequest::DB_ENTRY_ADD_CHANGE) {
1838 8179 : req.data.reset(new typename TableT::RequestData(
1839 : new_attr, flags, label, l3_label, 0));
1840 : }
1841 11615 : req.key.reset(new typename TableT::RequestKey(prefix, this));
1842 11615 : table->Enqueue(&req);
1843 : }
1844 9182 : }
1845 :
1846 : template <typename PrefixT>
1847 0 : void BgpPeer::ProcessNlriBgpaas(Address::Family family, DBRequest::DBOperation oper,
1848 : const BgpMpNlri *nlri, BgpAttrPtr attr, uint32_t flags) {
1849 :
1850 0 : for (vector<BgpProtoPrefix *>::const_iterator it = nlri->nlri.begin();
1851 0 : it != nlri->nlri.end(); ++it) {
1852 0 : PrefixT prefix;
1853 0 : BgpAttrPtr new_attr(attr);
1854 0 : uint32_t label = 0;
1855 0 : uint32_t l3_label = 0;
1856 0 : int result = PrefixT::FromProtoPrefix(server_, **it,
1857 0 : (oper == DBRequest::DB_ENTRY_ADD_CHANGE ? attr.get() : NULL),
1858 : family, &prefix, &new_attr, &label, &l3_label);
1859 0 : if (result) {
1860 0 : BGP_LOG_PEER_WARNING(Message, this,
1861 : BGP_LOG_FLAG_ALL, BGP_PEER_DIR_IN,
1862 : "MP NLRI parse error for " <<
1863 : Address::FamilyToString(family) << " route");
1864 0 : continue;
1865 0 : }
1866 :
1867 0 : ProcessBgpaas(oper, prefix.addr(), prefix.prefixlen(), new_attr, flags);
1868 : }
1869 0 : }
1870 :
1871 0 : void BgpPeer::ProcessBgpaas(DBRequest::DBOperation oper,
1872 : IpAddress addr, uint8_t addr_len, BgpAttrPtr attr, uint32_t flags) {
1873 :
1874 0 : if (rtinstance_->routing_instance_vxlan() == "") {
1875 0 : return;
1876 : }
1877 0 : RoutingInstanceMgr *mgr = server()->routing_instance_mgr();
1878 0 : if (mgr == nullptr) {
1879 0 : return;
1880 : }
1881 : RoutingInstance *vxlan_ri =
1882 0 : mgr->GetRoutingInstance(rtinstance_->routing_instance_vxlan());
1883 0 : if (vxlan_ri == nullptr) {
1884 0 : return;
1885 : }
1886 0 : EvpnTable *table = static_cast<EvpnTable *>(vxlan_ri->GetTable(Address::EVPN));
1887 0 : EvpnPrefix prefix_evpn(RouteDistinguisher::kZeroRd, addr, addr_len);
1888 :
1889 0 : DBRequest req;
1890 0 : req.oper = oper;
1891 0 : if (oper == DBRequest::DB_ENTRY_ADD_CHANGE) {
1892 0 : req.data.reset(new EvpnTable::RequestData(attr, flags, 0, 0, 0));
1893 : }
1894 : else {
1895 0 : req.data.reset(NULL);
1896 : }
1897 0 : req.key.reset(new EvpnTable::RequestKey(prefix_evpn, this));
1898 0 : table->Enqueue(&req);
1899 0 : }
1900 :
1901 6838 : uint32_t BgpPeer::GetPathFlags(Address::Family family,
1902 : const BgpAttr *attr) const {
1903 6838 : uint32_t flags = resolve_paths_ ? BgpPath::ResolveNexthop : 0;
1904 :
1905 : // Check for OriginatorId loop in case we are an RR client.
1906 6838 : if (peer_type_ == BgpProto::IBGP &&
1907 0 : attr->originator_id().to_ulong() == ntohl(local_bgp_id_)) {
1908 0 : flags |= BgpPath::OriginatorIdLooped;
1909 : }
1910 :
1911 : // Check for ClusterList loop in case we are an RR.
1912 6838 : if (server_->cluster_id() && attr->cluster_list() &&
1913 0 : attr->cluster_list()->cluster_list().ClusterListLoop(
1914 0 : server_->cluster_id())) {
1915 0 : flags |= BgpPath::ClusterListLooped;
1916 : }
1917 :
1918 6838 : if (!attr->as_path() && !attr->aspath_4byte())
1919 0 : return flags;
1920 :
1921 : // Check whether neighbor has appended its AS to the AS_PATH.
1922 20514 : if ((PeerType() == BgpProto::EBGP) &&
1923 20514 : ((attr->as_path() && !attr->as_path()->path().AsLeftMostMatch(
1924 13676 : peer_as())) || (attr->aspath_4byte() &&
1925 0 : !attr->aspath_4byte()->path().AsLeftMostMatch(peer_as())))) {
1926 0 : flags |= BgpPath::NoNeighborAs;
1927 : }
1928 :
1929 : // Check for AS_PATH loop.
1930 6838 : uint8_t max_loop_count = family_attributes_list_[family]->loop_count;
1931 6838 : if (attr->IsAsPathLoop(local_as_, max_loop_count))
1932 0 : flags |= BgpPath::AsPathLooped;
1933 :
1934 6838 : return flags;
1935 : }
1936 :
1937 9530 : uint32_t BgpPeer::GetLocalPrefFromMed(uint32_t med) const {
1938 9530 : if (peer_type_ != BgpProto::EBGP)
1939 0 : return 0;
1940 9530 : if (!peer_is_control_node_)
1941 9530 : return 0;
1942 0 : if (med == 0)
1943 0 : return 0;
1944 0 : if (med == 100)
1945 0 : return 200;
1946 0 : if (med == 200)
1947 0 : return 100;
1948 0 : return numeric_limits<uint32_t>::max() - med;
1949 : }
1950 :
1951 9529 : void BgpPeer::ProcessUpdate(const BgpProto::Update *msg, size_t msgsize) {
1952 9529 : BgpAttrPtr attr = server_->attr_db()->Locate(msg->path_attributes);
1953 :
1954 9530 : uint32_t local_pref = GetLocalPrefFromMed(attr->med());
1955 9530 : if (local_pref) {
1956 0 : attr = server_->attr_db()->ReplaceLocalPreferenceAndLocate(attr.get(),
1957 0 : local_pref);
1958 : }
1959 :
1960 : // Check if peer is marked to override the route origin attribute
1961 9530 : if (origin_override_.origin_override) {
1962 0 : attr = server_->attr_db()->ReplaceOriginAndLocate(attr.get(),
1963 0 : origin_override_.origin);
1964 : }
1965 :
1966 19060 : if ((router_type_ == "bgpaas-client") ||
1967 9530 : (router_type_ == "bgpaas-server")) {
1968 0 : attr = server_->attr_db()->ReplaceSubProtocolAndLocate(attr.get(),
1969 0 : MatchProtocolToString(MatchProtocol::BGPaaS));
1970 : }
1971 :
1972 9530 : uint32_t reach_count = 0, unreach_count = 0;
1973 9530 : RoutingInstance *instance = GetRoutingInstance();
1974 9530 : if (msg->nlri.size() || msg->withdrawn_routes.size()) {
1975 : InetTable *table =
1976 0 : static_cast<InetTable *>(instance->GetTable(Address::INET));
1977 0 : if (!table) {
1978 0 : BGP_LOG_WARNING_STR(BgpConfig, BGP_LOG_FLAG_ALL,
1979 : "Cannot find inet table");
1980 0 : return;
1981 : }
1982 :
1983 0 : unreach_count += msg->withdrawn_routes.size();
1984 0 : for (vector<BgpProtoPrefix *>::const_iterator it =
1985 0 : msg->withdrawn_routes.begin(); it != msg->withdrawn_routes.end();
1986 0 : ++it) {
1987 0 : Ip4Prefix prefix;
1988 0 : int result = Ip4Prefix::FromProtoPrefix((**it), &prefix);
1989 0 : if (result) {
1990 0 : BGP_LOG_PEER_WARNING(Message, this,
1991 : BGP_LOG_FLAG_ALL, BGP_PEER_DIR_IN,
1992 : "Withdrawn route parse error for inet route");
1993 0 : continue;
1994 0 : }
1995 :
1996 0 : if ((router_type_ == "bgpaas-client") ||
1997 0 : (router_type_ == "bgpaas-server")) {
1998 0 : ProcessBgpaas(DBRequest::DB_ENTRY_DELETE, prefix.addr(),
1999 0 : prefix.prefixlen(), attr, 0);
2000 : }
2001 :
2002 0 : DBRequest req;
2003 0 : req.oper = DBRequest::DB_ENTRY_DELETE;
2004 0 : req.data.reset(NULL);
2005 0 : req.key.reset(new InetTable::RequestKey(prefix, this));
2006 0 : table->Enqueue(&req);
2007 0 : }
2008 :
2009 0 : uint32_t flags = GetPathFlags(Address::INET, attr.get());
2010 0 : reach_count += msg->nlri.size();
2011 0 : for (vector<BgpProtoPrefix *>::const_iterator it = msg->nlri.begin();
2012 0 : it != msg->nlri.end(); ++it) {
2013 0 : Ip4Prefix prefix;
2014 0 : int result = Ip4Prefix::FromProtoPrefix((**it), &prefix);
2015 0 : if (result) {
2016 0 : BGP_LOG_PEER_WARNING(Message, this,
2017 : BGP_LOG_FLAG_ALL, BGP_PEER_DIR_IN,
2018 : "NLRI parse error for inet route");
2019 0 : continue;
2020 0 : }
2021 :
2022 0 : DBRequest req;
2023 0 : req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
2024 0 : req.data.reset(new InetTable::RequestData(attr, flags, 0, 0, 0));
2025 0 : req.key.reset(new InetTable::RequestKey(prefix, this));
2026 0 : table->Enqueue(&req);
2027 :
2028 0 : if ((router_type_ == "bgpaas-client") ||
2029 0 : (router_type_ == "bgpaas-server")) {
2030 0 : ProcessBgpaas(DBRequest::DB_ENTRY_ADD_CHANGE, prefix.addr(),
2031 0 : prefix.prefixlen(), attr, flags);
2032 : }
2033 0 : }
2034 : }
2035 :
2036 9530 : for (vector<BgpAttribute *>::const_iterator ait =
2037 9530 : msg->path_attributes.begin();
2038 42028 : ait != msg->path_attributes.end(); ++ait) {
2039 : DBRequest::DBOperation oper;
2040 32846 : if ((*ait)->code == BgpAttribute::MPReachNlri) {
2041 6838 : oper = DBRequest::DB_ENTRY_ADD_CHANGE;
2042 26008 : } else if ((*ait)->code == BgpAttribute::MPUnreachNlri) {
2043 2692 : oper = DBRequest::DB_ENTRY_DELETE;
2044 : } else {
2045 23316 : continue;
2046 : }
2047 :
2048 9530 : BgpMpNlri *nlri = static_cast<BgpMpNlri *>(*ait);
2049 9530 : assert(nlri);
2050 9530 : if (oper == DBRequest::DB_ENTRY_ADD_CHANGE) {
2051 6838 : reach_count += nlri->nlri.size();
2052 : } else {
2053 2692 : unreach_count += nlri->nlri.size();
2054 : }
2055 :
2056 9530 : Address::Family family = BgpAf::AfiSafiToFamily(nlri->afi, nlri->safi);
2057 9530 : if (!IsFamilyNegotiated(family)) {
2058 0 : BGP_LOG_PEER_NOTICE(Message, this,
2059 : BGP_LOG_FLAG_ALL, BGP_PEER_DIR_IN,
2060 : "AFI "<< nlri->afi << " SAFI " << (int) nlri->safi <<
2061 : " not allowed");
2062 0 : continue;
2063 0 : }
2064 :
2065 : // Handle EndOfRib marker.
2066 9530 : if (oper == DBRequest::DB_ENTRY_DELETE && nlri->nlri.empty()) {
2067 348 : inc_rx_end_of_rib();
2068 348 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
2069 : BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_IN,
2070 : "EndOfRib marker family " <<
2071 : Address::FamilyToString(family) <<
2072 : " size " << msgsize);
2073 348 : ReceiveEndOfRIB(family, msgsize);
2074 348 : return;
2075 : }
2076 :
2077 9182 : uint32_t flags = 0;
2078 9182 : if ((*ait)->code == BgpAttribute::MPReachNlri) {
2079 6838 : flags = GetPathFlags(family, attr.get());
2080 6838 : attr = GetMpNlriNexthop(nlri, attr);
2081 : }
2082 :
2083 9182 : switch (family) {
2084 0 : case Address::INET:
2085 : case Address::INETMPLS:
2086 0 : ProcessNlri<InetTable, Ip4Prefix>(
2087 : family, oper, nlri, attr, flags);
2088 0 : if ((router_type_ == "bgpaas-client") ||
2089 0 : (router_type_ == "bgpaas-server")) {
2090 0 : ProcessNlriBgpaas<Ip4Prefix>(
2091 : family, oper, nlri, attr, flags);
2092 : }
2093 0 : break;
2094 3744 : case Address::INETVPN:
2095 3744 : ProcessNlri<InetVpnTable, InetVpnPrefix>(
2096 : family, oper, nlri, attr, flags);
2097 3744 : break;
2098 0 : case Address::INET6:
2099 0 : ProcessNlri<Inet6Table, Inet6Prefix>(
2100 : family, oper, nlri, attr, flags);
2101 0 : if ((router_type_ == "bgpaas-client") ||
2102 0 : (router_type_ == "bgpaas-server")) {
2103 0 : ProcessNlriBgpaas<Inet6Prefix>(
2104 : family, oper, nlri, attr, flags);
2105 : }
2106 0 : break;
2107 3256 : case Address::INET6VPN:
2108 3256 : ProcessNlri<Inet6VpnTable, Inet6VpnPrefix>(
2109 : family, oper, nlri, attr, flags);
2110 3256 : break;
2111 1352 : case Address::EVPN:
2112 1352 : ProcessNlri<EvpnTable, EvpnPrefix>(
2113 : family, oper, nlri, attr, flags);
2114 1352 : break;
2115 0 : case Address::ERMVPN:
2116 0 : ProcessNlri<ErmVpnTable, ErmVpnPrefix>(
2117 : family, oper, nlri, attr, flags);
2118 0 : break;
2119 0 : case Address::MVPN:
2120 0 : ProcessNlri<MvpnTable, MvpnPrefix>(
2121 : family, oper, nlri, attr, flags);
2122 0 : break;
2123 830 : case Address::RTARGET:
2124 830 : ProcessNlri<RTargetTable, RTargetPrefix>(
2125 : family, oper, nlri, attr, flags);
2126 830 : break;
2127 0 : default:
2128 0 : break;
2129 : }
2130 : }
2131 :
2132 9182 : inc_rx_route_reach(reach_count);
2133 9182 : inc_rx_route_unreach(unreach_count);
2134 9182 : if (Sandesh::LoggingLevel() >= Sandesh::LoggingUtLevel()) {
2135 9182 : BGP_LOG_PEER(Message, this, Sandesh::LoggingUtLevel(),
2136 : BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_IN,
2137 : "Update size " << msgsize <<
2138 : " reach " << reach_count << " unreach " << unreach_count);
2139 : }
2140 9530 : }
2141 31563 : const std::vector<std::string> BgpPeer::GetDefaultTunnelEncap(
2142 : const Address::Family family) const {
2143 31563 : if (family_attributes_list_[family] == NULL)
2144 23034 : return std::vector<std::string>();
2145 8528 : return family_attributes_list_[family]->default_tunnel_encap_list;
2146 : }
2147 :
2148 31565 : void BgpPeer::ProcessPathTunnelEncapsulation(const BgpPath *path, BgpAttr *attr,
2149 : ExtCommunityDB *extcomm_db,
2150 : const BgpTable *table) const {
2151 31565 : if (!GetDefaultTunnelEncap(table->family()).empty()) {
2152 0 : ExtCommunityPtr ext_community = attr->ext_community();
2153 0 : bool tunnel_encap_found = false;
2154 0 : if (ext_community) {
2155 0 : for (ExtCommunity::ExtCommunityList::const_iterator iter =
2156 0 : attr->ext_community()->communities().begin();
2157 0 : iter != attr->ext_community()->communities().end();
2158 0 : ++iter) {
2159 0 : if (ExtCommunity::is_tunnel_encap(*iter)) {
2160 0 : tunnel_encap_found = true;
2161 0 : break;
2162 : }
2163 : }
2164 : }
2165 : // Set default tunnel encap since it is not in the path
2166 0 : if (!ext_community || !tunnel_encap_found) {
2167 0 : ExtCommunity::ExtCommunityList encap_list;
2168 0 : BOOST_FOREACH(const string &encap_string,
2169 : GetDefaultTunnelEncap(table->family())) {
2170 0 : TunnelEncap tunnel_encap(encap_string);
2171 0 : encap_list.push_back(tunnel_encap.GetExtCommunity());
2172 0 : }
2173 : ext_community =
2174 0 : extcomm_db->ReplaceTunnelEncapsulationAndLocate(
2175 0 : ext_community ? ext_community.get() : NULL, encap_list);
2176 0 : attr->set_ext_community(ext_community);
2177 0 : }
2178 0 : }
2179 31548 : }
2180 :
2181 :
2182 17064 : void BgpPeer::UpdatePrimaryPathCount(int count, Address::Family family) const {
2183 17064 : primary_path_count_ += count;
2184 17067 : if (family == Address::UNSPEC)
2185 0 : return;
2186 17067 : family_primary_path_count_[family] += count;
2187 17066 : uint32_t limit = 0;
2188 17066 : if (family_attributes_list_[family])
2189 17066 : limit = family_attributes_list_[family]->prefix_limit;
2190 17066 : if (limit && family_primary_path_count_[family] > limit)
2191 0 : TriggerPrefixLimitCheck();
2192 : }
2193 :
2194 0 : void BgpPeer::StartPrefixLimitIdleTimer(uint32_t plim_idle_time_msecs) {
2195 0 : prefix_limit_idle_timer_->Start(plim_idle_time_msecs,
2196 : boost::bind(&BgpPeer::PrefixLimitIdleTimerExpired, this),
2197 : boost::bind(&BgpPeer::PrefixLimitIdleTimerErrorHandler, this, _1, _2));
2198 0 : }
2199 :
2200 0 : void BgpPeer::StopPrefixLimitIdleTimer() {
2201 0 : prefix_limit_idle_timer_->Cancel();
2202 0 : }
2203 :
2204 215 : bool BgpPeer::PrefixLimitIdleTimerRunning() const {
2205 215 : return prefix_limit_idle_timer_->running();
2206 : }
2207 :
2208 0 : bool BgpPeer::PrefixLimitIdleTimerExpired() {
2209 0 : return false;
2210 : }
2211 :
2212 0 : void BgpPeer::PrefixLimitIdleTimerErrorHandler(string error_name,
2213 : string error_message) {
2214 0 : BGP_LOG_PEER_CRITICAL(Timer, this, BGP_LOG_FLAG_ALL, BGP_PEER_DIR_NA,
2215 : "Timer error: " << error_name << " " << error_message);
2216 0 : }
2217 :
2218 0 : void BgpPeer::EndOfRibTimerErrorHandler(string error_name,
2219 : string error_message) {
2220 0 : BGP_LOG_PEER_CRITICAL(Timer, this, BGP_LOG_FLAG_ALL, BGP_PEER_DIR_NA,
2221 : "Timer error: " << error_name << " " << error_message);
2222 0 : }
2223 :
2224 74 : void BgpPeer::RegisterToVpnTables() {
2225 74 : CHECK_CONCURRENCY("bgp::StateMachine", "bgp::RTFilter", "bgp::Config");
2226 :
2227 74 : if (vpn_tables_registered_)
2228 8 : return;
2229 66 : vpn_tables_registered_ = true;
2230 :
2231 66 : RoutingInstance *instance = GetRoutingInstance();
2232 : vector<Address::Family> vpn_family_list = list_of
2233 66 : (Address::INETVPN)(Address::INET6VPN)(Address::ERMVPN)(Address::EVPN)
2234 66 : (Address::MVPN);
2235 726 : BOOST_FOREACH(Address::Family vpn_family, vpn_family_list) {
2236 330 : if (!IsFamilyNegotiated(vpn_family))
2237 66 : continue;
2238 264 : BgpTable *table = instance->GetTable(vpn_family);
2239 400 : BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_TRACE,
2240 : table, "Register peer with the table");
2241 264 : Register(table, BuildRibExportPolicy(vpn_family));
2242 : }
2243 66 : }
2244 :
2245 664 : void BgpPeer::StartEndOfRibReceiveTimer(Address::Family family) {
2246 664 : uint32_t timeout = GetEndOfRibReceiveTime(family);
2247 :
2248 664 : BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO,
2249 : BGP_LOG_FLAG_SYSLOG, BGP_PEER_DIR_OUT,
2250 : "EndOfRib Receive Timer scheduled for family " <<
2251 : Address::FamilyToString(family) <<
2252 : " to fire after " << timeout << " second(s)");
2253 664 : eor_receive_timer_[family]->Start(timeout * 1000,
2254 : boost::bind(&BgpPeer::EndOfRibReceiveTimerExpired, this, family),
2255 : boost::bind(&BgpPeer::EndOfRibTimerErrorHandler, this, _1, _2));
2256 664 : }
2257 :
2258 0 : void BgpPeer::KeepaliveTimerErrorHandler(string error_name,
2259 : string error_message) {
2260 0 : BGP_LOG_PEER_CRITICAL(Timer, this, BGP_LOG_FLAG_ALL, BGP_PEER_DIR_NA,
2261 : "Timer error: " << error_name << " " << error_message);
2262 0 : }
2263 :
2264 0 : bool BgpPeer::EndOfRibReceiveTimerExpired(Address::Family family) {
2265 0 : if (family == Address::RTARGET)
2266 0 : RegisterToVpnTables();
2267 :
2268 : // Fake reception of EoRs to exit from GR states and sweep all stale routes.
2269 0 : close_manager_->ProcessEORMarkerReceived(family);
2270 0 : return false;
2271 : }
2272 :
2273 0 : bool BgpPeer::KeepaliveTimerExpired() {
2274 0 : if (!IsReady())
2275 0 : return false;
2276 :
2277 0 : SendKeepalive(true);
2278 :
2279 : //
2280 : // Start the timer again, by returning true
2281 : //
2282 0 : return true;
2283 : }
2284 :
2285 8345 : void BgpPeer::StartKeepaliveTimerUnlocked() {
2286 8345 : int keepalive_time_msecs = state_machine_->keepalive_time_msecs();
2287 8345 : if (keepalive_time_msecs <= 0)
2288 0 : return;
2289 :
2290 8345 : keepalive_timer_->Start(keepalive_time_msecs,
2291 : boost::bind(&BgpPeer::KeepaliveTimerExpired, this),
2292 : boost::bind(&BgpPeer::KeepaliveTimerErrorHandler, this, _1, _2));
2293 : }
2294 :
2295 80 : void BgpPeer::StartKeepaliveTimer() {
2296 80 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
2297 80 : if (session_ && send_ready_)
2298 80 : StartKeepaliveTimerUnlocked();
2299 80 : }
2300 :
2301 0 : void BgpPeer::StopKeepaliveTimerUnlocked() {
2302 0 : keepalive_timer_->Cancel();
2303 0 : }
2304 :
2305 0 : bool BgpPeer::KeepaliveTimerRunning() {
2306 0 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
2307 0 : return keepalive_timer_->running();
2308 0 : }
2309 :
2310 0 : void BgpPeer::SetSendReady() {
2311 0 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
2312 0 : BGP_LOG_PEER(Event, this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_ALL,
2313 : BGP_PEER_DIR_NA, "Send ready");
2314 0 : send_ready_ = true;
2315 0 : if (session_ != NULL)
2316 0 : StartKeepaliveTimerUnlocked();
2317 0 : }
2318 :
2319 80 : void BgpPeer::set_session(BgpSession *session) {
2320 80 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
2321 80 : assert(session_ == NULL);
2322 80 : session_ = session;
2323 80 : }
2324 :
2325 216 : void BgpPeer::clear_session() {
2326 216 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
2327 216 : if (session_) {
2328 80 : session_->clear_peer();
2329 80 : session_->set_observer(NULL);
2330 80 : session_->Close();
2331 : }
2332 216 : session_ = NULL;
2333 216 : }
2334 :
2335 800 : BgpSession *BgpPeer::session() {
2336 800 : return session_;
2337 : }
2338 :
2339 1094 : string BgpPeer::BytesToHexString(const u_int8_t *msg, size_t size) {
2340 1094 : ostringstream out;
2341 : char buf[4];
2342 :
2343 90798 : for (size_t i = 0; i < size; i ++) {
2344 89704 : if (!(i % 32)) out << "\n";
2345 89704 : if (!(i % 4)) out << " 0x";
2346 89704 : snprintf(buf, sizeof(buf), "%02X", msg[i]);
2347 89704 : out << buf;
2348 : }
2349 :
2350 1094 : out << "\n";
2351 :
2352 2188 : return out.str();
2353 1094 : }
2354 :
2355 9841 : bool BgpPeer::ReceiveMsg(BgpSession *session, const u_int8_t *msg,
2356 : size_t size) {
2357 9841 : ParseErrorContext ec;
2358 19681 : BgpProto::BgpMessage *minfo = BgpProto::Decode(msg, size, &ec,
2359 9841 : Is4ByteAsSupported());
2360 :
2361 9840 : if (minfo == NULL) {
2362 0 : BGP_TRACE_PEER_PACKET(this, msg, size, SandeshLevel::SYS_WARN);
2363 0 : BGP_LOG_PEER_WARNING(Message, this, BGP_LOG_FLAG_ALL,
2364 : BGP_PEER_DIR_IN,
2365 : "Error while parsing message at " << ec.type_name);
2366 0 : state_machine_->OnMessageError(session, &ec);
2367 0 : return false;
2368 : }
2369 :
2370 : // Tracing periodic keepalive packets is not necessary.
2371 9840 : if (minfo->type != BgpProto::KEEPALIVE)
2372 9760 : BGP_TRACE_PEER_PACKET(this, msg, size, SandeshLevel::SYS_WARN); //Sandesh::LoggingUtLevel()
2373 :
2374 9841 : state_machine_->OnMessage(session, minfo, size);
2375 9841 : return true;
2376 9841 : }
2377 :
2378 : //
2379 : // Extract nexthop address from BgpMpNlri if appropriate and return updated
2380 : // BgpAttrPtr. The original attribute is returned for cases where there's no
2381 : // nexthop attribute in the BgpMpNlri.
2382 : //
2383 6838 : BgpAttrPtr BgpPeer::GetMpNlriNexthop(BgpMpNlri *nlri, BgpAttrPtr attr) {
2384 6838 : bool update_nh = false;
2385 6838 : IpAddress addr;
2386 :
2387 6838 : if (nlri->afi == BgpAf::IPv4) {
2388 3554 : if (nlri->safi == BgpAf::Mpls || nlri->safi == BgpAf::Unicast ||
2389 3554 : nlri->safi == BgpAf::RTarget || nlri->safi == BgpAf::MVpn) {
2390 802 : Ip4Address::bytes_type bt = { { 0 } };
2391 1604 : copy(nlri->nexthop.begin(),
2392 802 : nlri->nexthop.begin() + sizeof(bt), bt.begin());
2393 802 : addr = Ip4Address(bt);
2394 802 : update_nh = true;
2395 3554 : } else if (nlri->safi == BgpAf::Vpn) {
2396 2752 : Ip4Address::bytes_type bt = { { 0 } };
2397 2752 : size_t rdsize = RouteDistinguisher::kSize;
2398 5504 : copy(nlri->nexthop.begin() + rdsize,
2399 2752 : nlri->nexthop.begin() + rdsize + sizeof(bt), bt.begin());
2400 2752 : addr = Ip4Address(bt);
2401 2752 : update_nh = true;
2402 : }
2403 3284 : } else if (nlri->afi == BgpAf::L2Vpn) {
2404 956 : if (nlri->safi == BgpAf::EVpn) {
2405 956 : Ip4Address::bytes_type bt = { { 0 } };
2406 1912 : copy(nlri->nexthop.begin(),
2407 956 : nlri->nexthop.begin() + sizeof(bt), bt.begin());
2408 956 : addr = Ip4Address(bt);
2409 956 : update_nh = true;
2410 : }
2411 2328 : } else if (nlri->afi == BgpAf::IPv6) {
2412 2328 : if (nlri->safi == BgpAf::Unicast) {
2413 : // There could be either 1 or 2 v6 addresses in the nexthop field.
2414 : // The first one is supposed to be global and the optional second
2415 : // one, if present, is link local. We will be liberal and find the
2416 : // global address, whether it's first or second. Further, if the
2417 : // address is a v4-mapped v6 address, we use the corresponding v4
2418 : // address as the nexthop.
2419 0 : for (int idx = 0; idx < 2; ++idx) {
2420 0 : Ip6Address::bytes_type bt = { { 0 } };
2421 0 : if ((idx + 1) * sizeof(bt) > nlri->nexthop.size())
2422 0 : break;
2423 0 : copy(nlri->nexthop.begin() + idx * sizeof(bt),
2424 0 : nlri->nexthop.begin() + (idx + 1) * sizeof(bt), bt.begin());
2425 0 : Ip6Address v6_addr(bt);
2426 0 : if (v6_addr.is_v4_mapped()) {
2427 0 : addr = Address::V4FromV4MappedV6(v6_addr);
2428 0 : update_nh = true;
2429 0 : break;
2430 : }
2431 0 : if (!v6_addr.is_link_local()) {
2432 0 : addr = v6_addr;
2433 0 : update_nh = true;
2434 0 : break;
2435 : }
2436 : }
2437 2328 : } else if (nlri->safi == BgpAf::Vpn) {
2438 2328 : Ip6Address::bytes_type bt = { { 0 } };
2439 2328 : size_t rdsize = RouteDistinguisher::kSize;
2440 4656 : copy(nlri->nexthop.begin() + rdsize,
2441 2328 : nlri->nexthop.begin() + rdsize + sizeof(bt), bt.begin());
2442 2328 : Ip6Address v6_addr(bt);
2443 2328 : if (v6_addr.is_v4_mapped()) {
2444 2328 : addr = Address::V4FromV4MappedV6(v6_addr);
2445 2328 : update_nh = true;
2446 : }
2447 : }
2448 : }
2449 :
2450 : // Always update the nexthop in BgpAttr with MpReachNlri->nexthop.
2451 : // NOP in cases <afi,safi> doesn't carry nexthop attribute.
2452 6838 : if (update_nh) {
2453 6838 : attr = server_->attr_db()->ReplaceNexthopAndLocate(attr.get(), addr);
2454 : }
2455 13676 : return attr;
2456 : }
2457 :
2458 32 : void BgpPeer::ManagedDelete() {
2459 32 : if (deleter_->IsDeleted())
2460 0 : return;
2461 32 : BGP_LOG_PEER(Config, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
2462 : BGP_PEER_DIR_NA, "Received request for deletion");
2463 32 : if (IsRouterTypeBGPaaS()) {
2464 0 : server()->increment_deleting_bgpaas_count();
2465 : } else {
2466 32 : server()->increment_deleting_count();
2467 : }
2468 32 : deleter_->Delete();
2469 : }
2470 :
2471 96 : void BgpPeer::RetryDelete() {
2472 96 : if (!deleter_->IsDeleted())
2473 32 : return;
2474 64 : deleter_->RetryDelete();
2475 : }
2476 :
2477 1136 : int BgpPeer::GetTaskInstance() const {
2478 1136 : return index_ % TaskScheduler::GetInstance()->HardwareThreadCount();
2479 : }
2480 :
2481 1094 : void BgpPeer::SetDataCollectionKey(BgpPeerInfo *peer_info) const {
2482 1094 : if (rtinstance_) {
2483 1094 : peer_info->set_domain(rtinstance_->name());
2484 : } else {
2485 0 : peer_info->set_domain(BgpConfigManager::kMasterInstance);
2486 : }
2487 :
2488 1094 : peer_info->set_ip_address(peer_key_.endpoint.address().to_string());
2489 1094 : }
2490 :
2491 0 : static void FillProtoStats(const IPeerDebugStats::ProtoStats &stats,
2492 : PeerProtoStats *proto_stats) {
2493 0 : proto_stats->set_open(stats.open);
2494 0 : proto_stats->set_keepalive(stats.keepalive);
2495 0 : proto_stats->set_close(stats.close);
2496 0 : proto_stats->set_update(stats.update);
2497 0 : proto_stats->set_notification(stats.notification);
2498 0 : proto_stats->set_total(stats.open + stats.keepalive + stats.close +
2499 0 : stats.update + stats.notification);
2500 0 : }
2501 :
2502 0 : static void FillRouteUpdateStats(const IPeerDebugStats::UpdateStats &stats,
2503 : PeerUpdateStats *rt_stats) {
2504 0 : rt_stats->set_reach(stats.reach);
2505 0 : rt_stats->set_unreach(stats.unreach);
2506 0 : rt_stats->set_end_of_rib(stats.end_of_rib);
2507 0 : rt_stats->set_total(stats.reach + stats.unreach + stats.end_of_rib);
2508 0 : }
2509 :
2510 0 : static void FillSocketStats(const IPeerDebugStats::SocketStats &socket_stats,
2511 : PeerSocketStats *peer_socket_stats) {
2512 0 : peer_socket_stats->set_calls(socket_stats.calls);
2513 0 : peer_socket_stats->set_bytes(socket_stats.bytes);
2514 0 : if (socket_stats.calls) {
2515 0 : peer_socket_stats->set_average_bytes(
2516 0 : socket_stats.bytes/socket_stats.calls);
2517 : }
2518 0 : peer_socket_stats->set_blocked_count(socket_stats.blocked_count);
2519 0 : ostringstream os;
2520 0 : os << boost::posix_time::microseconds(long(socket_stats.blocked_duration_usecs));
2521 0 : peer_socket_stats->set_blocked_duration(os.str());
2522 0 : if (socket_stats.blocked_count) {
2523 0 : os.str("");
2524 0 : os << boost::posix_time::microseconds(
2525 0 : socket_stats.blocked_duration_usecs/socket_stats.blocked_count);
2526 0 : peer_socket_stats->set_average_blocked_duration(os.str());
2527 : }
2528 0 : }
2529 :
2530 0 : void BgpPeer::FillCloseInfo(BgpNeighborResp *resp) const {
2531 0 : close_manager_->FillCloseInfo(resp);
2532 0 : }
2533 :
2534 0 : void BgpPeer::FillBgpNeighborDebugState(BgpNeighborResp *bnr,
2535 : const IPeerDebugStats *peer_stats) {
2536 0 : bnr->set_last_state(peer_stats->last_state());
2537 0 : bnr->set_last_event(peer_stats->last_event());
2538 0 : bnr->set_last_error(peer_stats->last_error());
2539 0 : bnr->set_last_state_at(peer_stats->last_state_change_at());
2540 0 : bnr->set_flap_count(peer_stats->num_flaps());
2541 0 : bnr->set_flap_time(peer_stats->last_flap());
2542 :
2543 0 : IPeerDebugStats::ProtoStats stats;
2544 0 : PeerProtoStats proto_stats;
2545 0 : peer_stats->GetRxProtoStats(&stats);
2546 0 : FillProtoStats(stats, &proto_stats);
2547 0 : bnr->set_rx_proto_stats(proto_stats);
2548 :
2549 0 : peer_stats->GetTxProtoStats(&stats);
2550 0 : FillProtoStats(stats, &proto_stats);
2551 0 : bnr->set_tx_proto_stats(proto_stats);
2552 :
2553 0 : IPeerDebugStats::UpdateStats update_stats;
2554 0 : PeerUpdateStats rt_stats;
2555 0 : peer_stats->GetRxRouteUpdateStats(&update_stats);
2556 0 : FillRouteUpdateStats(update_stats, &rt_stats);
2557 0 : bnr->set_rx_update_stats(rt_stats);
2558 :
2559 0 : peer_stats->GetTxRouteUpdateStats(&update_stats);
2560 0 : FillRouteUpdateStats(update_stats, &rt_stats);
2561 0 : bnr->set_tx_update_stats(rt_stats);
2562 :
2563 0 : IPeerDebugStats::SocketStats socket_stats;
2564 0 : PeerSocketStats peer_socket_stats;
2565 :
2566 0 : peer_stats->GetRxSocketStats(&socket_stats);
2567 0 : FillSocketStats(socket_stats, &peer_socket_stats);
2568 0 : bnr->set_rx_socket_stats(peer_socket_stats);
2569 :
2570 0 : peer_stats->GetTxSocketStats(&socket_stats);
2571 0 : FillSocketStats(socket_stats, &peer_socket_stats);
2572 0 : bnr->set_tx_socket_stats(peer_socket_stats);
2573 0 : }
2574 :
2575 0 : void BgpPeer::FillBgpNeighborFamilyAttributes(BgpNeighborResp *nbr) const {
2576 0 : vector<ShowBgpNeighborFamily> show_family_attributes_list;
2577 0 : for (int idx = Address::UNSPEC; idx < Address::NUM_FAMILIES; ++idx) {
2578 0 : if (!family_attributes_list_[idx])
2579 0 : continue;
2580 0 : ShowBgpNeighborFamily show_family_attributes;
2581 0 : show_family_attributes.set_family(
2582 0 : Address::FamilyToString(static_cast<Address::Family>(idx)));
2583 0 : show_family_attributes.set_loop_count(
2584 0 : family_attributes_list_[idx]->loop_count);
2585 0 : show_family_attributes.set_prefix_limit(
2586 0 : family_attributes_list_[idx]->prefix_limit);
2587 0 : show_family_attributes.set_idle_timeout(
2588 0 : family_attributes_list_[idx]->idle_timeout);
2589 0 : if (!family_attributes_list_[idx]->gateway_address.is_unspecified()) {
2590 0 : show_family_attributes.set_gateway_address(
2591 0 : family_attributes_list_[idx]->gateway_address.to_string());
2592 : }
2593 0 : show_family_attributes_list.push_back(show_family_attributes);
2594 0 : }
2595 0 : nbr->set_family_attributes_list(show_family_attributes_list);
2596 0 : }
2597 :
2598 0 : void BgpPeer::FillNeighborInfo(const BgpSandeshContext *bsc,
2599 : BgpNeighborResp *bnr, bool summary) const {
2600 0 : bnr->set_instance_name(rtinstance_->name());
2601 0 : bnr->set_peer(peer_basename_);
2602 0 : bnr->set_deleted(IsDeleted());
2603 0 : bnr->set_closed_at(UTCUsecToString(deleter_->delete_time_stamp_usecs()));
2604 0 : bnr->set_admin_down(admin_down_);
2605 0 : bnr->set_passive(passive_);
2606 0 : bnr->set_as_override(as_override_);
2607 0 : bnr->set_origin_override(origin_override_.origin_override);
2608 0 : if (origin_override_.origin_override) {
2609 0 : bnr->set_route_origin(BgpAttr::OriginToString(origin_override_.origin));
2610 : } else {
2611 0 : bnr->set_route_origin("-");
2612 : }
2613 0 : bnr->set_private_as_action(private_as_action_);
2614 0 : bnr->set_peer_address(peer_address_string());
2615 0 : bnr->set_peer_id(bgp_identifier_string());
2616 0 : bnr->set_peer_asn(peer_as());
2617 0 : bnr->set_peer_port(peer_port());
2618 0 : bnr->set_transport_address(transport_address_string());
2619 0 : bnr->set_encoding("BGP");
2620 0 : bnr->set_peer_type(PeerType() == BgpProto::IBGP ? "internal" : "external");
2621 0 : bnr->set_router_type(router_type_);
2622 0 : bnr->set_state(state_machine_->StateName());
2623 0 : bnr->set_local_address(server_->ToString());
2624 0 : bnr->set_local_id(Ip4Address(ntohl(local_bgp_id_)).to_string());
2625 0 : bnr->set_local_asn(local_as());
2626 0 : bnr->set_cluster_id(Ip4Address(cluster_id_).to_string());
2627 0 : bnr->set_negotiated_hold_time(state_machine_->hold_time());
2628 0 : bnr->set_primary_path_count(GetPrimaryPathCount());
2629 0 : bnr->set_task_instance(GetTaskInstance());
2630 0 : bnr->set_send_ready(send_ready_);
2631 0 : bnr->set_flap_count(peer_stats_->num_flaps());
2632 0 : bnr->set_as4_supported(Is4ByteAsSupported());
2633 0 : bnr->set_flap_time(peer_stats_->last_flap());
2634 0 : bnr->set_auth_type(
2635 0 : AuthenticationData::KeyTypeToString(inuse_authkey_type_));
2636 0 : if (bsc->test_mode()) {
2637 0 : bnr->set_auth_keys(auth_data_.KeysToStringDetail());
2638 : }
2639 :
2640 0 : if (summary)
2641 0 : return;
2642 :
2643 0 : bnr->set_configured_address_families(configured_families_);
2644 0 : bnr->set_negotiated_address_families(negotiated_families_);
2645 :
2646 0 : peer_close_->FillNeighborInfo(bnr);
2647 :
2648 0 : bnr->set_configured_hold_time(state_machine_->GetConfiguredHoldTime());
2649 0 : FillBgpNeighborFamilyAttributes(bnr);
2650 0 : FillBgpNeighborDebugState(bnr, peer_stats_.get());
2651 0 : BgpMembershipManager *mgr = server_->membership_mgr();
2652 0 : mgr->FillPeerMembershipInfo(this, bnr);
2653 0 : bnr->set_routing_instances(vector<BgpNeighborRoutingInstance>());
2654 0 : FillCloseInfo(bnr);
2655 : }
2656 :
2657 98 : void BgpPeer::inc_rx_open() {
2658 98 : peer_stats_->proto_stats_[0].open++;
2659 98 : }
2660 :
2661 188 : void BgpPeer::inc_tx_open() {
2662 188 : peer_stats_->proto_stats_[1].open++;
2663 188 : }
2664 :
2665 80 : void BgpPeer::inc_rx_keepalive() {
2666 80 : peer_stats_->proto_stats_[0].keepalive++;
2667 80 : }
2668 :
2669 0 : uint64_t BgpPeer::get_rx_keepalive() const {
2670 0 : return peer_stats_->proto_stats_[0].keepalive;
2671 : }
2672 :
2673 80 : void BgpPeer::inc_tx_keepalive() {
2674 80 : peer_stats_->proto_stats_[1].keepalive++;
2675 80 : }
2676 :
2677 0 : uint64_t BgpPeer::get_tx_keepalive() const {
2678 0 : return peer_stats_->proto_stats_[1].keepalive;
2679 : }
2680 :
2681 9539 : void BgpPeer::inc_rx_update() {
2682 9539 : peer_stats_->proto_stats_[0].update++;
2683 9539 : }
2684 :
2685 0 : uint64_t BgpPeer::get_rx_update() const {
2686 0 : return peer_stats_->proto_stats_[0].update;
2687 : }
2688 :
2689 10746 : void BgpPeer::inc_tx_update() {
2690 10746 : peer_stats_->proto_stats_[1].update++;
2691 10746 : }
2692 :
2693 0 : uint64_t BgpPeer::get_tx_update() const {
2694 0 : return peer_stats_->proto_stats_[1].update;
2695 : }
2696 :
2697 124 : void BgpPeer::inc_rx_notification() {
2698 124 : peer_stats_->proto_stats_[0].notification++;
2699 124 : }
2700 :
2701 0 : uint64_t BgpPeer::get_rx_notification() const {
2702 0 : return peer_stats_->proto_stats_[0].notification;
2703 : }
2704 :
2705 86 : void BgpPeer::inc_tx_notification() {
2706 86 : peer_stats_->proto_stats_[1].notification++;
2707 86 : }
2708 :
2709 348 : void BgpPeer::inc_rx_end_of_rib() {
2710 348 : peer_stats_->update_stats_[0].end_of_rib++;
2711 348 : }
2712 :
2713 0 : uint64_t BgpPeer::get_rx_end_of_rib() const {
2714 0 : return peer_stats_->update_stats_[0].end_of_rib;
2715 : }
2716 :
2717 356 : void BgpPeer::inc_tx_end_of_rib() {
2718 356 : peer_stats_->update_stats_[1].end_of_rib++;
2719 356 : }
2720 :
2721 0 : uint64_t BgpPeer::get_tx_end_of_rib() const {
2722 0 : return peer_stats_->update_stats_[1].end_of_rib;
2723 : }
2724 :
2725 9182 : void BgpPeer::inc_rx_route_reach(uint64_t count) {
2726 9182 : peer_stats_->update_stats_[0].reach += count;
2727 9182 : }
2728 :
2729 0 : uint64_t BgpPeer::get_rx_route_reach() const {
2730 0 : return peer_stats_->update_stats_[0].reach;
2731 : }
2732 :
2733 0 : uint64_t BgpPeer::get_tx_route_reach() const {
2734 0 : return peer_stats_->update_stats_[1].reach;
2735 : }
2736 :
2737 9182 : void BgpPeer::inc_rx_route_unreach(uint64_t count) {
2738 9182 : peer_stats_->update_stats_[0].unreach += count;
2739 9182 : }
2740 :
2741 0 : uint64_t BgpPeer::get_rx_route_unreach() const {
2742 0 : return peer_stats_->update_stats_[0].unreach;
2743 : }
2744 :
2745 0 : uint64_t BgpPeer::get_tx_route_unreach() const {
2746 0 : return peer_stats_->update_stats_[1].unreach;
2747 : }
2748 :
2749 0 : uint64_t BgpPeer::get_rx_route_total() const {
2750 0 : return peer_stats_->update_stats_[0].reach +
2751 0 : peer_stats_->update_stats_[0].unreach +
2752 0 : peer_stats_->update_stats_[0].end_of_rib;
2753 : }
2754 :
2755 0 : uint64_t BgpPeer::get_tx_route_total() const {
2756 0 : return peer_stats_->update_stats_[1].reach +
2757 0 : peer_stats_->update_stats_[1].unreach +
2758 0 : peer_stats_->update_stats_[1].end_of_rib;
2759 : }
2760 :
2761 0 : void BgpPeer::inc_connect_error() {
2762 0 : peer_stats_->error_stats_.connect_error++;
2763 0 : }
2764 :
2765 0 : void BgpPeer::inc_connect_timer_expired() {
2766 0 : peer_stats_->error_stats_.connect_timer++;
2767 0 : }
2768 :
2769 0 : void BgpPeer::inc_hold_timer_expired() {
2770 0 : peer_stats_->error_stats_.hold_timer++;
2771 0 : }
2772 :
2773 0 : void BgpPeer::inc_open_error() {
2774 0 : peer_stats_->error_stats_.open_error++;
2775 0 : }
2776 :
2777 0 : void BgpPeer::inc_update_error() {
2778 0 : peer_stats_->error_stats_.update_error++;
2779 0 : }
2780 :
2781 0 : uint64_t BgpPeer::get_connect_error() const {
2782 0 : return peer_stats_->error_stats_.connect_error;
2783 : }
2784 :
2785 0 : uint64_t BgpPeer::get_connect_timer_expired() const {
2786 0 : return peer_stats_->error_stats_.connect_timer;
2787 : }
2788 :
2789 0 : uint64_t BgpPeer::get_hold_timer_expired() const {
2790 0 : return peer_stats_->error_stats_.hold_timer;
2791 : }
2792 :
2793 0 : uint64_t BgpPeer::get_open_error() const {
2794 0 : return peer_stats_->error_stats_.open_error;
2795 : }
2796 :
2797 0 : uint64_t BgpPeer::get_update_error() const {
2798 0 : return peer_stats_->error_stats_.update_error;
2799 : }
2800 :
2801 0 : uint64_t BgpPeer::get_socket_reads() const {
2802 0 : IPeerDebugStats::SocketStats stats;
2803 0 : peer_stats_->GetRxSocketStats(&stats);
2804 0 : return stats.calls;
2805 : }
2806 :
2807 0 : uint64_t BgpPeer::get_socket_writes() const {
2808 0 : IPeerDebugStats::SocketStats stats;
2809 0 : peer_stats_->GetTxSocketStats(&stats);
2810 0 : return stats.calls;
2811 : }
2812 :
2813 0 : string BgpPeer::last_flap_at() const {
2814 0 : if (last_flap_) {
2815 0 : return integerToString(UTCUsecToPTime(last_flap_));
2816 : } else {
2817 0 : return "";
2818 : }
2819 : }
2820 :
2821 79 : void BgpPeer::increment_flap_count() {
2822 79 : flap_count_++;
2823 79 : total_flap_count_++;
2824 79 : last_flap_ = UTCTimestampUsec();
2825 :
2826 160 : BgpPeerInfoData peer_info;
2827 80 : peer_info.set_name(ToUVEKey());
2828 80 : PeerFlapInfo flap_info;
2829 80 : flap_info.set_flap_count(flap_count_);
2830 80 : flap_info.set_flap_time(last_flap_);
2831 80 : peer_info.set_flap_info(flap_info);
2832 80 : BGPPeerInfoSend(peer_info);
2833 :
2834 160 : PeerFlapData peer_flap_data;
2835 80 : peer_flap_data.set_name(ToUVEKey());
2836 80 : peer_flap_data.set_flap_info(flap_info);
2837 80 : assert(!peer_flap_data.get_name().empty());
2838 80 : BGP_UVE_SEND2(PeerFlap, peer_flap_data, "ObjectBgpPeer");
2839 80 : }
2840 :
2841 16 : void BgpPeer::reset_flap_count() {
2842 16 : flap_count_ = 0;
2843 16 : last_flap_ = 0;
2844 :
2845 32 : BgpPeerInfoData peer_info;
2846 16 : peer_info.set_name(ToUVEKey());
2847 16 : PeerFlapInfo flap_info;
2848 16 : peer_info.set_flap_info(flap_info);
2849 16 : BGPPeerInfoSend(peer_info);
2850 :
2851 32 : PeerFlapData peer_flap_data;
2852 16 : peer_flap_data.set_name(ToUVEKey());
2853 16 : peer_flap_data.set_flap_info(flap_info);
2854 16 : assert(!peer_flap_data.get_name().empty());
2855 16 : BGP_UVE_SEND2(PeerFlap, peer_flap_data, "ObjectBgpPeer");
2856 16 : }
2857 :
2858 : // Ignore if the peer is IBGP and a BGPaaS client since we do not support that
2859 : // combination. i.e, allow any EBGP session or any non BGPaaS-client session.
2860 60 : bool BgpPeer::ProcessSession() const {
2861 60 : return PeerType() != BgpProto::IBGP || router_type() != "bgpaas-client";
2862 : }
2863 :
2864 : // Update control DSCP
2865 0 : void BgpPeer::DSCPUpdateCallback(uint8_t dscp_value) {
2866 0 : if ((session_ != NULL) && (dscp_value != 0xFF)) {
2867 0 : session_->SetDscpSocketOption(dscp_value);
2868 : }
2869 0 : }
|