LCOV - code coverage report
Current view: top level - bgp - bgp_peer.cc (source / functions) Hit Total Coverage
Test: OpenSDN C/C++ coverage (all TARGET_SET jobs) Lines: 1105 1777 62.2 %
Date: 2026-11-23 02:04:52 Functions: 129 210 61.4 %
Legend: Lines: hit not hit

          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         102 :     explicit PeerStats(BgpPeer *peer)
      58         510 :         : peer_(peer) {
      59         102 :     }
      60             : 
      61             :     // Used when peer flaps.
      62             :     // Reset all counters.
      63             :     // Socket counters are implicitly cleared because we use a new socket.
      64         498 :     virtual void Clear() {
      65         498 :         error_stats_ = ErrorStats();
      66         498 :         proto_stats_[0] = ProtoStats();
      67         498 :         proto_stats_[1] = ProtoStats();
      68         498 :         update_stats_[0] = UpdateStats();
      69         498 :         update_stats_[1] = UpdateStats();
      70         498 :     }
      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        4615 :     virtual void UpdateTxUnreachRoute(uint64_t count) {
     138        4615 :         update_stats_[1].unreach += count;
     139        4615 :     }
     140             : 
     141        4614 :     virtual void UpdateTxReachRoute(uint64_t count) {
     142        4614 :         update_stats_[1].reach += count;
     143        4614 :     }
     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         102 :     explicit DeleteActor(BgpPeer *peer)
     166         102 :         : LifetimeActor(peer->server_->lifetime_manager()),
     167         102 :           peer_(peer) {
     168         102 :     }
     169             : 
     170         271 :     virtual bool MayDelete() const {
     171         271 :         CHECK_CONCURRENCY("bgp::Config");
     172         271 :         if (!peer_->close_manager_->IsQueueEmpty())
     173          67 :             return false;
     174         204 :         if (peer_->IsCloseInProgress())
     175           0 :             return false;
     176         204 :         if (!peer_->state_machine_->IsQueueEmpty())
     177         102 :             return false;
     178         102 :         if (peer_->prefix_limit_trigger_.IsSet())
     179           0 :             return false;
     180         102 :         return true;
     181             :     }
     182             : 
     183         102 :     virtual void Shutdown() {
     184         102 :         CHECK_CONCURRENCY("bgp::Config");
     185         102 :         peer_->Clear(BgpProto::Notification::PeerDeconfigured);
     186         102 :     }
     187             : 
     188         102 :     virtual void Destroy() {
     189         102 :         CHECK_CONCURRENCY("bgp::Config");
     190         102 :         peer_->PostCloseRelease();
     191         102 :         if (peer_->IsRouterTypeBGPaaS()) {
     192          34 :             peer_->server()->decrement_deleting_bgpaas_count();
     193             :         } else {
     194          68 :             peer_->server()->decrement_deleting_count();
     195             :         }
     196         102 :         if (peer_->dscp_listener_id_ >= 0) {
     197         102 :             peer_->server()->UnregisterDSCPUpdateCallback(
     198         102 :                                         peer_->dscp_listener_id_);
     199         102 :             peer_->dscp_listener_id_ = -1;
     200             :         }
     201         102 :         if (peer_->instance_op_ >= 0) {
     202          34 :             peer_->server()->routing_instance_mgr()->
     203          34 :                 UnregisterInstanceOpCallback(peer_->instance_op_);
     204          34 :             peer_->instance_op_ = -1;
     205             :         }
     206         102 :         if (peer_->asn_listener_id_ >= 0) {
     207          34 :             peer_->server()->UnregisterASNUpdateCallback(
     208          34 :                 peer_->asn_listener_id_);
     209          34 :             peer_->asn_listener_id_ = -1;
     210             :         }
     211         102 :         assert(!peer_->membership_req_pending());
     212         102 :         assert(!peer_->close_manager_->IsMembershipInUse());
     213         102 :         peer_->rtinstance_->peer_manager()->DestroyIPeer(peer_);
     214         102 :     }
     215             : 
     216             : private:
     217             :     BgpPeer *peer_;
     218             : };
     219             : 
     220             : //
     221             : // Constructor for BgpPeerFamilyAttributes.
     222             : //
     223         400 : BgpPeerFamilyAttributes::BgpPeerFamilyAttributes(
     224             :     const BgpNeighborConfig *config,
     225         400 :     const BgpFamilyAttributesConfig &family_config) {
     226         400 :     if (family_config.loop_count) {
     227           0 :         loop_count = family_config.loop_count;
     228             :     } else {
     229         400 :         loop_count = config->loop_count();
     230             :     }
     231         400 :     prefix_limit = family_config.prefix_limit;
     232         400 :     idle_timeout = family_config.idle_timeout;
     233         400 :     default_tunnel_encap_list = family_config.default_tunnel_encap_list;
     234             : 
     235         400 :     if (config->router_type() == "bgpaas-client") {
     236         132 :         if (family_config.family == "inet") {
     237          66 :             gateway_address = config->gateway_address(Address::INET);
     238          66 :         } else if (family_config.family == "inet6") {
     239          66 :             gateway_address = config->gateway_address(Address::INET6);
     240             :         }
     241             :     }
     242         400 : }
     243             : 
     244         692 : RibExportPolicy BgpPeer::BuildRibExportPolicy(Address::Family family) const {
     245         692 :     RibExportPolicy policy;
     246             :     BgpPeerFamilyAttributes *family_attributes =
     247         692 :         family_attributes_list_[family];
     248         692 :     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         692 :         policy = RibExportPolicy(peer_type_, RibExportPolicy::BGP, peer_as_,
     254         692 :             as_override_, peer_close_->IsCloseLongLivedGraceful(),
     255         692 :             as4_supported_, family_attributes->gateway_address,
     256         692 :             -1, cluster_id_, family_attributes->default_tunnel_encap_list,
     257        1384 :             local_as_);
     258             :     }
     259             : 
     260         692 :     if (private_as_action_ == "remove") {
     261           0 :         policy.SetRemovePrivatePolicy(false, false, true);
     262         692 :     } else if (private_as_action_ == "remove-all") {
     263           0 :         policy.SetRemovePrivatePolicy(true, false, true);
     264         692 :     } else if (private_as_action_ == "replace-all") {
     265           0 :         policy.SetRemovePrivatePolicy(true, true, true);
     266             :     }
     267             : 
     268         692 :     return policy;
     269           0 : }
     270             : 
     271         688 : void BgpPeer::ReceiveEndOfRIB(Address::Family family, size_t msgsize) {
     272         688 :     close_manager_->ProcessEORMarkerReceived(family);
     273         688 :     eor_receive_timer_[family]->Cancel();
     274             : 
     275             :     // If EoR for RTarget is received, start registration for other families.
     276         688 :     if (family == Address::RTARGET)
     277           0 :         RegisterToVpnTables();
     278         688 : }
     279             : 
     280         690 : void BgpPeer::SendEndOfRIBActual(Address::Family family) {
     281         690 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     282             : 
     283             :     // Bail if there's no session for the peer anymore.
     284         690 :     if (!session_)
     285           0 :         return;
     286             : 
     287         690 :     BgpProto::Update update;
     288             :     uint16_t afi;
     289             :     uint8_t safi;
     290         690 :     tie(afi, safi) = BgpAf::FamilyToAfiSafi(family);
     291         690 :     BgpMpNlri *nlri = new BgpMpNlri(BgpAttribute::MPUnreachNlri, afi, safi);
     292         690 :     update.path_attributes.push_back(nlri);
     293             :     uint8_t data[256];
     294        1380 :     int msgsize = BgpProto::Encode(&update, data, sizeof(data), NULL,
     295         690 :                                    Is4ByteAsSupported());
     296         690 :     assert(msgsize > BgpProto::kMinMessageSize);
     297         690 :     session_->Send(data, msgsize, NULL);
     298         690 :     inc_tx_end_of_rib();
     299         690 :     inc_tx_update();
     300         690 :     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         690 : }
     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         789 : uint32_t BgpPeer::GetEndOfRibReceiveTime(Address::Family family) const {
     316         789 :     return family == Address::RTARGET ?
     317         789 :         kRouteTargetEndOfRibTimeSecs : server_->GetEndOfRibReceiveTime();
     318             : }
     319             : 
     320        1055 : bool BgpPeer::IsServerStartingUp() const {
     321        1055 :     return server_->IsServerStartingUp();
     322             : }
     323             : 
     324         136 : bool BgpPeer::IsCloseGraceful() const {
     325         136 :     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        1170 : void BgpPeer::BGPPeerInfoSend(const BgpPeerInfoData &peer_info) const {
     418        1170 :     assert(!peer_info.get_name().empty());
     419        1170 :     BGP_UVE_SEND(BGPPeerInfo, peer_info);
     420        1170 : }
     421             : 
     422         629 : bool BgpPeer::CanUseMembershipManager() const {
     423         629 :     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        2239 : void BgpPeer::MembershipRequestCallback(BgpTable *table) {
     432        2239 :     if (close_manager_->IsMembershipInUse()) {
     433        1547 :         close_manager_->MembershipRequestCallback();
     434        1547 :         return;
     435             :     }
     436             : 
     437         692 :     assert(membership_req_pending_ > 0);
     438         692 :     membership_req_pending_--;
     439             : 
     440             :     // Resume if CloseManager is waiting to use membership manager.
     441        1190 :     if (!membership_req_pending_ &&
     442         498 :         close_manager_->IsMembershipInWait()) {
     443           0 :         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         692 :     if (defer_close_) {
     449           2 :         if (!membership_req_pending_) {
     450           2 :             defer_close_ = false;
     451           2 :             trigger_.Set();
     452             :         }
     453           2 :         return;
     454             :     }
     455             : 
     456         690 :     SendEndOfRIB(table->family());
     457             : }
     458             : 
     459        2870 : bool BgpPeer::MembershipPathCallback(DBTablePartBase *tpart, BgpRoute *route,
     460             :                                      BgpPath *path) {
     461        2870 :     return close_manager_->MembershipPathCallback(tpart, route, path);
     462             : }
     463             : 
     464           2 : bool BgpPeer::ResumeClose() {
     465           2 :     peer_close_->Close(graceful_close_);
     466           2 :     graceful_close_ = true;
     467           2 :     return true;
     468             : }
     469             : 
     470         102 : BgpPeer::BgpPeer(BgpServer *server, RoutingInstance *instance,
     471         102 :                  const BgpNeighborConfig *config)
     472         102 :         : server_(server),
     473         102 :           rtinstance_(instance),
     474         102 :           peer_key_(config),
     475         102 :           peer_port_(config->source_port()),
     476         102 :           peer_name_(config->name()),
     477         102 :           router_type_(config->router_type()),
     478         102 :           config_(config),
     479         102 :           index_(server->RegisterPeer(this)),
     480         102 :           trigger_(boost::bind(&BgpPeer::ResumeClose, this),
     481             :                    TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
     482             :                    GetTaskInstance()),
     483         102 :           prefix_limit_idle_timer_(
     484         102 :               TimerManager::CreateTimer(*server->ioservice(),
     485             :               "BGP prefix limit idle timer",
     486             :               TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
     487             :               GetTaskInstance())),
     488         102 :           prefix_limit_trigger_(boost::bind(&BgpPeer::CheckPrefixLimits, this),
     489             :                    TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
     490             :                    GetTaskInstance()),
     491         102 :           buffer_capacity_(GetBufferCapacity()),
     492         102 :           session_(NULL),
     493         102 :           keepalive_timer_(TimerManager::CreateTimer(*server->ioservice(),
     494             :                      "BGP keepalive timer",
     495             :                    TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
     496             :                    GetTaskInstance())),
     497         102 :           eor_send_timer_start_time_(0),
     498         102 :           send_ready_(true),
     499         102 :           admin_down_(config->admin_down()),
     500         102 :           passive_(config->passive()),
     501         102 :           resolve_paths_(config->router_type() == "bgpaas-client"),
     502         102 :           as_override_(config->as_override()),
     503         102 :           cluster_id_(config->cluster_id()),
     504         102 :           origin_override_(config->origin_override()),
     505         102 :           defer_close_(false),
     506         102 :           graceful_close_(true),
     507         102 :           as4_supported_(false),
     508         102 :           vpn_tables_registered_(false),
     509         102 :           hold_time_(config->hold_time()),
     510         102 :           local_as_(config->local_as()),
     511         102 :           peer_as_(config->peer_as()),
     512         102 :           local_bgp_id_(config->local_identifier()),
     513         102 :           peer_bgp_id_(0),
     514         102 :           peer_type_((config->peer_as() == config->local_as()) ?
     515             :                          BgpProto::IBGP : BgpProto::EBGP),
     516         102 :           state_machine_(BgpStaticObjectFactory::Create<StateMachine>(this)),
     517         102 :           peer_close_(BgpStaticObjectFactory::Create<BgpPeerClose>(this)),
     518         102 :           peer_stats_(new PeerStats(this)),
     519         102 :           deleter_(new DeleteActor(this)),
     520         102 :           instance_delete_ref_(this, instance ? instance->deleter() : NULL),
     521         102 :           flap_count_(0),
     522         102 :           total_flap_count_(0),
     523         102 :           last_flap_(0),
     524         102 :           dscp_listener_id_(-1),
     525         102 :           inuse_authkey_type_(AuthenticationData::NIL),
     526         102 :           asn_listener_id_(-1),
     527        2040 :           instance_op_(-1) {
     528         102 :     buffer_.reserve(buffer_capacity_);
     529         102 :     close_manager_.reset(
     530         102 :         BgpStaticObjectFactory::Create<PeerCloseManager>(static_cast<IPeerClose*>(peer_close_.get())));
     531         102 :     ostringstream oss1;
     532         102 :     oss1 << peer_key_.endpoint.address();
     533         102 :     if (peer_key_.endpoint.port() != BgpConfigManager::kDefaultPort)
     534          68 :         oss1 << ":" << dec << peer_key_.endpoint.port();
     535         102 :     to_str_ = oss1.str();
     536             : 
     537         102 :     ostringstream oss2;
     538         102 :     if (rtinstance_)
     539         102 :         oss2 << rtinstance_->name() << ":";
     540         102 :     oss2 << server_->localname() << ":";
     541         102 :     oss2 << peer_name();
     542         102 :     uve_key_str_ = oss2.str();
     543             : 
     544         204 :     if (router_type_ == "control-node" ||
     545         102 :         router_type_ == "external-control-node") {
     546           0 :         peer_is_control_node_ = true;
     547             :     } else {
     548         102 :         peer_is_control_node_ = false;
     549             :     }
     550             : 
     551         102 :     dscp_listener_id_ = server_->RegisterDSCPUpdateCallback(boost::bind(
     552             :         &BgpPeer::DSCPUpdateCallback, this, _1));
     553         102 :     if (IsRouterTypeBGPaaS()) {
     554          34 :         asn_listener_id_ = server->RegisterASNUpdateCallback(boost::bind(
     555             :             &BgpPeer::ASNUpdateCallback, this, _1, _2));
     556          34 :         instance_op_=server->routing_instance_mgr()->RegisterInstanceOpCallback(
     557             :                 boost::bind(&BgpPeer::RoutingInstanceCallback, this, _1, _2));
     558             :     }
     559             : 
     560         102 :     membership_req_pending_ = 0;
     561         102 :     BGP_LOG_PEER(Event, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
     562             :         BGP_PEER_DIR_NA, "Created");
     563             : 
     564         102 :     if (rtinstance_ && peer_name_.find(rtinstance_->name()) == 0) {
     565         102 :         peer_basename_ = peer_name_.substr(rtinstance_->name().size() + 1);
     566             :     } else {
     567           0 :         peer_basename_ = peer_name_;
     568             :     }
     569             : 
     570         102 :     for (Address::Family family = Address::UNSPEC;
     571        1122 :             family < Address::NUM_FAMILIES;
     572        1020 :             family = static_cast<Address::Family>(family + 1)) {
     573        1020 :         family_primary_path_count_[family] = 0;
     574        2040 :         eor_send_timer_[family] =
     575        3060 :             TimerManager::CreateTimer(*server->ioservice(),
     576        2040 :                 "BGP EoR Send timer for " + Address::FamilyToString(family),
     577             :                 TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
     578             :                 GetTaskInstance());
     579        2040 :         eor_receive_timer_[family] =
     580        3060 :             TimerManager::CreateTimer(*server->ioservice(),
     581        2040 :                 "BGP EoR Receive timer for " + Address::FamilyToString(family),
     582             :                 TaskScheduler::GetInstance()->GetTaskId("bgp::StateMachine"),
     583             :                 GetTaskInstance());
     584             :     }
     585             : 
     586         102 :     total_path_count_ = 0;
     587         102 :     primary_path_count_ = 0;
     588             : 
     589             :     // Check rtinstance_ to accommodate unit tests.
     590         102 :     if (resolve_paths_ && rtinstance_) {
     591          34 :         rtinstance_->GetTable(Address::INET)->LocatePathResolver();
     592          34 :         rtinstance_->GetTable(Address::INET6)->LocatePathResolver();
     593             :     }
     594             : 
     595         102 :     ProcessEndpointConfig(config);
     596         102 :     ProcessAuthKeyChainConfig(config);
     597         102 :     ProcessFamilyAttributesConfig(config);
     598             : 
     599         204 :     BgpPeerInfoData peer_info;
     600         102 :     peer_info.set_name(ToUVEKey());
     601         102 :     peer_info.set_admin_down(admin_down_);
     602         102 :     peer_info.set_passive(passive_);
     603         102 :     peer_info.set_as_override(as_override_);
     604         102 :     peer_info.set_origin_override(origin_override_.origin_override);
     605         102 :     if (origin_override_.origin_override) {
     606           0 :         peer_info.set_route_origin(
     607           0 :             BgpAttr::OriginToString(origin_override_.origin));
     608             :     } else {
     609         102 :         peer_info.set_route_origin("-");
     610             :     }
     611         102 :     peer_info.set_router_type(router_type_);
     612         102 :     peer_info.set_cluster_id(Ip4Address(cluster_id_).to_string());
     613         204 :     peer_info.set_peer_type(
     614         102 :         PeerType() == BgpProto::IBGP ? "internal" : "external");
     615         102 :     peer_info.set_local_asn(local_as_);
     616         102 :     peer_info.set_peer_asn(peer_as_);
     617         102 :     peer_info.set_peer_port(peer_port_);
     618         102 :     peer_info.set_hold_time(hold_time_);
     619         102 :     peer_info.set_local_id(local_bgp_id_);
     620         102 :     peer_info.set_configured_families(configured_families_);
     621         102 :     peer_info.set_peer_address(peer_key_.endpoint.address().to_string());
     622         102 :     BGPPeerInfoSend(peer_info);
     623         102 : }
     624             : 
     625         102 : BgpPeer::~BgpPeer() {
     626         102 :     assert(!close_manager()->IsCloseInProgress());
     627         102 :     assert(!IsCloseInProgress());
     628         102 :     assert(GetTotalPathCount() == 0);
     629         102 :     STLDeleteValues(&family_attributes_list_);
     630         102 :     ClearListenSocketAuthKey();
     631         204 :     BgpPeerInfoData peer_info;
     632         102 :     peer_info.set_name(ToUVEKey());
     633         102 :     peer_info.set_deleted(true);
     634         102 :     BGPPeerInfoSend(peer_info);
     635             : 
     636         204 :     PeerStatsData peer_stats_data;
     637         102 :     peer_stats_data.set_name(ToUVEKey());
     638         102 :     peer_stats_data.set_deleted(true);
     639         102 :     assert(!peer_stats_data.get_name().empty());
     640         102 :     BGP_UVE_SEND2(PeerStatsUve, peer_stats_data, "ObjectBgpPeer");
     641             : 
     642         204 :     PeerFlapData peer_flap_data;
     643         102 :     peer_flap_data.set_name(ToUVEKey());
     644         102 :     peer_flap_data.set_deleted(true);
     645         102 :     assert(!peer_flap_data.get_name().empty());
     646         102 :     BGP_UVE_SEND2(PeerFlap, peer_flap_data, "ObjectBgpPeer");
     647             : 
     648         102 :     BGP_LOG_PEER(Event, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
     649             :         BGP_PEER_DIR_NA, "Deleted");
     650         102 : }
     651             : 
     652         102 : void BgpPeer::Initialize() {
     653         102 :     if (!admin_down_)
     654         102 :         state_machine_->Initialize();
     655         102 : }
     656             : 
     657         102 : size_t BgpPeer::GetBufferCapacity() const {
     658             :     // For testing only - configure through environment variable.
     659         102 :     char *buffer_capacity_str = getenv("BGP_PEER_BUFFER_SIZE");
     660         102 :     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         102 :     if (IsRouterTypeBGPaaS()) {
     671          34 :         return kMinBufferCapacity;
     672             :     } else {
     673          68 :         return kMaxBufferCapacity;
     674             :     }
     675             : }
     676             : 
     677        2885 : bool BgpPeer::CheckSplitHorizon(uint32_t server_cluster_id,
     678             :         uint32_t ribout_cid) const {
     679        2885 :     if (PeerType() == BgpProto::IBGP) {
     680             :         // check if router is a route reflector
     681        2885 :         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         164 : BgpTable *BgpPeer::GetRTargetTable() {
     695         164 :     RoutingInstanceMgr *instance_mgr = server_->routing_instance_mgr();
     696         164 :     if (!instance_mgr)
     697           0 :         return NULL;
     698         164 :     RoutingInstance *master = instance_mgr->GetDefaultRoutingInstance();
     699         164 :     if (!master)
     700           0 :         return NULL;
     701         164 :     return master->GetTable(Address::RTARGET);
     702             : }
     703             : 
     704          97 : BgpAttrPtr BgpPeer::GetRouteTargetRouteAttr() const {
     705          97 :     BgpAttrSpec attrs;
     706          97 :     BgpAttrNextHop nexthop(server_->bgp_identifier());
     707          97 :     attrs.push_back(&nexthop);
     708          97 :     BgpAttrOrigin origin(BgpAttrOrigin::IGP);
     709          97 :     attrs.push_back(&origin);
     710         194 :     return server_->attr_db()->Locate(attrs);
     711          97 : }
     712             : 
     713             : // Add one route-target route to bgp.rtarget.0 table.
     714         291 : void BgpPeer::BGPaaSAddRTarget(as_t as, BgpTable *table, BgpAttrPtr attr,
     715             :                                RouteTargetList::const_iterator it) {
     716         291 :     const RouteTarget rtarget = *it;
     717         291 :     DBRequest req;
     718         291 :     RTargetPrefix rt_prefix(as, rtarget);
     719         291 :     req.key.reset(new RTargetTable::RequestKey(rt_prefix, this));
     720         291 :     req.data.reset(new RTargetTable::RequestData(attr, 0, 0, 0, 0));
     721         291 :     req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
     722         291 :     table->Enqueue(&req);
     723         291 : }
     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          97 : void BgpPeer::AddRTargets(as_t as) {
     728          97 :     if (!IsRouterTypeBGPaaS())
     729           0 :         return;
     730          97 :     assert(IsReady());
     731          97 :     BgpTable *table = GetRTargetTable();
     732          97 :     assert(table);
     733          97 :     BgpAttrPtr attr = GetRouteTargetRouteAttr();
     734          97 :     rtargets_ = rtinstance_->GetImportList();
     735          97 :     for (RouteTargetList::const_iterator it = rtargets_.begin();
     736         388 :             it != rtargets_.end(); it++) {
     737         291 :         BGPaaSAddRTarget(as, table, attr, it);
     738             :     }
     739          97 : }
     740             : 
     741             : // Delete one route-target route from bgp.rtarget.0 table.
     742          99 : void BgpPeer::BGPaaSDeleteRTarget(as_t as, BgpTable *table,
     743             :                                   RouteTargetList::const_iterator it) {
     744          99 :     const RouteTarget rtarget = *it;
     745          99 :     DBRequest req;
     746          99 :     RTargetPrefix rt_prefix(as, rtarget);
     747          99 :     req.key.reset(new RTargetTable::RequestKey(rt_prefix, this));
     748          99 :     req.oper = DBRequest::DB_ENTRY_DELETE;
     749          99 :     table->Enqueue(&req);
     750          99 : }
     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         165 : void BgpPeer::DeleteRTargets(as_t as) {
     756         165 :     if (!IsRouterTypeBGPaaS())
     757          98 :         return;
     758          67 :     BgpTable *table = GetRTargetTable();
     759          67 :     if (!table)
     760          34 :         return;
     761          33 :     for (RouteTargetList::const_iterator it = rtargets_.begin();
     762         132 :             it != rtargets_.end(); it++) {
     763          99 :         BGPaaSDeleteRTarget(as, table, it);
     764             :     }
     765          33 :     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         136 : void BgpPeer::RoutingInstanceCallback(const std::string &vrf_name, int op) {
     780         136 :     assert(IsRouterTypeBGPaaS());
     781         136 :     if (op != RoutingInstanceMgr::INSTANCE_UPDATE || !IsReady())
     782         136 :         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         996 : void BgpPeer::NotifyEstablished(bool established) {
     799         996 :     if (established) {
     800         498 :         if (IsRouterTypeBGPaaS()) {
     801          97 :             server_->IncrementUpBgpaasPeerCount();
     802          97 :             AddRTargets(server_->local_autonomous_system());
     803             :         } else {
     804         401 :             server_->IncrementUpPeerCount();
     805             :         }
     806             :     } else {
     807         498 :         if (IsRouterTypeBGPaaS()) {
     808          97 :             server_->DecrementUpBgpaasPeerCount();
     809             :         } else {
     810         401 :             server_->DecrementUpPeerCount();
     811             :         }
     812             :     }
     813         996 : }
     814             : 
     815           0 : void BgpPeer::BindLocalEndpoint(BgpSession *session) {
     816           0 : }
     817             : 
     818             : // Just return the first entry for now.
     819          54 : bool BgpPeer::GetBestAuthKey(AuthenticationKey *auth_key,
     820             :     KeyType *key_type) const {
     821          54 :     if (auth_data_.Empty()) {
     822           0 :         return false;
     823             :     }
     824          54 :     assert(auth_key);
     825          54 :     AuthenticationData::const_iterator iter = auth_data_.begin();
     826          54 :     *auth_key = *iter;
     827          54 :     *key_type = auth_data_.key_type();
     828          54 :     return true;
     829             : }
     830             : 
     831         234 : bool BgpPeer::ProcessAuthKeyChainConfig(const BgpNeighborConfig *config) {
     832         234 :     const AuthenticationData &input_auth_data = config->auth_data();
     833             : 
     834         234 :     if (auth_data_ == input_auth_data) {
     835         180 :         return false;
     836             :     }
     837             : 
     838          54 :     auth_data_ = input_auth_data;
     839          54 :     return InstallAuthKeys();
     840             : }
     841             : 
     842          54 : bool BgpPeer::InstallAuthKeys() {
     843          54 :     if (!PeerAddress()) {
     844           0 :         return false;
     845             :     }
     846             : 
     847          54 :     AuthenticationKey auth_key;
     848             :     KeyType key_type;
     849          54 :     bool valid = GetBestAuthKey(&auth_key, &key_type);
     850          54 :     if (valid) {
     851          54 :         if (key_type == AuthenticationData::MD5) {
     852          54 :             LogInstallAuthKeys("Listen", "add", auth_key, key_type);
     853          54 :             SetListenSocketAuthKey(auth_key, key_type);
     854          54 :             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          54 :     return true;
     868          54 : }
     869             : 
     870          54 : void BgpPeer::SetInuseAuthKeyInfo(const AuthenticationKey &key, KeyType type) {
     871          54 :     inuse_auth_key_ = key;
     872          54 :     inuse_authkey_type_ = type;
     873          54 : }
     874             : 
     875           0 : void BgpPeer::ResetInuseAuthKeyInfo() {
     876           0 :     inuse_auth_key_.Reset();
     877           0 :     inuse_authkey_type_ = AuthenticationData::NIL;
     878           0 : }
     879             : 
     880          54 : void BgpPeer::SetListenSocketAuthKey(const AuthenticationKey &auth_key,
     881             :                                      KeyType key_type) {
     882          54 :     if (key_type == AuthenticationData::MD5) {
     883          54 :         server_->session_manager()->
     884          54 :             SetListenSocketMd5Option(PeerAddress(), auth_key.value);
     885             :     }
     886          54 : }
     887             : 
     888         102 : void BgpPeer::ClearListenSocketAuthKey() {
     889         102 :     if (inuse_authkey_type_ == AuthenticationData::MD5) {
     890          54 :         server_->session_manager()->SetListenSocketMd5Option(PeerAddress(), "");
     891             :     }
     892         102 : }
     893             : 
     894        1578 : void BgpPeer::SetSessionSocketAuthKey(TcpSession *session) {
     895        1578 :     if ((inuse_authkey_type_ == AuthenticationData::MD5) && PeerAddress()) {
     896         793 :         assert(!inuse_auth_key_.value.empty());
     897         793 :         LogInstallAuthKeys("Session", "add", inuse_auth_key_,
     898             :                            inuse_authkey_type_);
     899         793 :         session->SetMd5SocketOption(PeerAddress(), inuse_auth_key_.value);
     900             :     }
     901        1578 : }
     902             : 
     903         772 : void BgpPeer::SetSessionSocketOptionDscp(TcpSession *session) {
     904         772 :     uint8_t dscp_value = server_->global_qos()->control_dscp();
     905             : 
     906         772 :     if (!session->socket()) {
     907           0 :         return;
     908             :     }
     909         772 :    if (dscp_value != 0xFF) {
     910         772 :         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         847 : void BgpPeer::LogInstallAuthKeys(const string &socket_name,
     919             :         const string &oper, const AuthenticationKey &auth_key,
     920             :         KeyType key_type) {
     921        1694 :     string logstr = socket_name + " socket kernel " + oper + " of key id "
     922        3388 :                           + integerToString(auth_key.id) + ", type "
     923        1694 :                           + AuthenticationData::KeyTypeToString(key_type)
     924        2541 :                           + ", peer " + peer_name_;
     925         847 :     BGP_LOG_PEER(Config, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
     926             :                  BGP_PEER_DIR_NA, logstr);
     927         847 : }
     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         132 : bool BgpPeer::CheckPrefixLimits() {
     935         132 :     RetryDelete();
     936         132 :     if (!IsReady())
     937          85 :         return true;
     938         512 :     for (size_t idx = Address::UNSPEC; idx < Address::NUM_FAMILIES; ++idx) {
     939             :         BgpPeerFamilyAttributes *family_attributes =
     940         465 :             family_attributes_list_[idx];
     941         465 :         if (!family_attributes || family_attributes->prefix_limit == 0)
     942         465 :             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          46 :     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         234 : bool BgpPeer::ProcessFamilyAttributesConfig(const BgpNeighborConfig *config) {
     959         234 :     FamilyAttributesList family_attributes_list(Address::NUM_FAMILIES);
     960        1034 :     BOOST_FOREACH(const BgpFamilyAttributesConfig family_config,
     961             :         config->family_attributes_list()) {
     962             :         Address::Family family =
     963         400 :             Address::FamilyFromString(family_config.family);
     964         400 :         assert(family != Address::UNSPEC);
     965             :         BgpPeerFamilyAttributes *family_attributes =
     966         400 :             new BgpPeerFamilyAttributes(config, family_config);
     967         400 :         family_attributes_list[family] = family_attributes;
     968         400 :     }
     969             : 
     970         234 :     int ret = STLSortedCompare(
     971             :         family_attributes_list.begin(), family_attributes_list.end(),
     972             :         family_attributes_list_.begin(), family_attributes_list_.end(),
     973             :         BgpPeerFamilyAttributesCompare());
     974         234 :     STLDeleteValues(&family_attributes_list_);
     975         234 :     family_attributes_list_ = family_attributes_list;
     976         234 :     configured_families_ = config->GetAddressFamilies();
     977         234 :     return (ret != 0);
     978         234 : }
     979             : 
     980         234 : void BgpPeer::ProcessEndpointConfig(const BgpNeighborConfig *config) {
     981         234 :     if (config->router_type() == "bgpaas-client") {
     982          66 :         endpoint_ = TcpSession::Endpoint(Ip4Address(), config->source_port());
     983             :     } else {
     984         168 :         endpoint_ = TcpSession::Endpoint();
     985             :     }
     986         234 : }
     987             : 
     988         132 : void BgpPeer::TriggerPrefixLimitCheck() const {
     989         132 :     prefix_limit_trigger_.Set();
     990         132 : }
     991             : 
     992         132 : void BgpPeer::ConfigUpdate(const BgpNeighborConfig *config) {
     993         132 :     if (IsDeleted())
     994           0 :         return;
     995             : 
     996         132 :     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         132 :     if (!config_)
    1001           0 :         return;
    1002             : 
    1003         132 :     bool clear_session = false;
    1004         132 :     bool admin_down_changed = false;
    1005         264 :     BgpPeerInfoData peer_info;
    1006         132 :     peer_info.set_name(ToUVEKey());
    1007             : 
    1008         132 :     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         132 :     if (passive_ != config->passive()) {
    1015           0 :         passive_ = config->passive();
    1016           0 :         peer_info.set_passive(passive_);
    1017           0 :         clear_session = true;
    1018             :     }
    1019             : 
    1020         132 :     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         132 :     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         132 :     OriginOverride origin_override(config->origin_override());
    1033         132 :     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         132 :     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         264 :     if (router_type_ == "control-node" ||
    1051         132 :         router_type_ == "external-control-node") {
    1052           0 :         peer_is_control_node_ = true;
    1053             :     } else {
    1054         132 :         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         132 :     BgpPeerKey key(config);
    1062         132 :     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         132 :     if (ProcessAuthKeyChainConfig(config)) {
    1069           0 :         clear_session = true;
    1070             :     }
    1071             : 
    1072         132 :     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         132 :     ProcessEndpointConfig(config);
    1078             : 
    1079         132 :     if (local_as_ != config->local_as()) {
    1080          48 :         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          48 :         local_as_ = config->local_as();
    1087          48 :         peer_info.set_local_asn(local_as_);
    1088          48 :         clear_session = true;
    1089             :     }
    1090             : 
    1091         132 :     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         132 :     if (peer_as_ != config->peer_as()) {
    1104          48 :         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          48 :         peer_as_ = config->peer_as();
    1111          48 :         peer_info.set_peer_asn(peer_as_);
    1112          48 :         clear_session = true;
    1113             :     }
    1114             : 
    1115         132 :     boost::system::error_code ec;
    1116         132 :     uint32_t local_bgp_id = config->local_identifier();
    1117         132 :     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         132 :     BgpProto::BgpPeerType old_type = PeerType();
    1124         132 :     peer_type_ = (peer_as_ == local_as_) ? BgpProto::IBGP : BgpProto::EBGP;
    1125         132 :     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         132 :     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         132 :     if (ProcessFamilyAttributesConfig(config)) {
    1139           0 :         peer_info.set_configured_families(configured_families_);
    1140           0 :         clear_session = true;
    1141             :     } else {
    1142         132 :         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         132 :     if (!admin_down_changed && !admin_down_ && clear_session) {
    1149          64 :         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          64 :         Clear(BgpProto::Notification::OtherConfigChange);
    1153             :     }
    1154             : 
    1155             :     // Send the UVE as appropriate.
    1156         132 :     if (admin_down_changed || clear_session) {
    1157          64 :         StopPrefixLimitIdleTimer();
    1158          64 :         BGPPeerInfoSend(peer_info);
    1159             :     }
    1160         132 : }
    1161             : 
    1162           0 : void BgpPeer::ClearConfig() {
    1163           0 :     CHECK_CONCURRENCY("bgp::Config");
    1164           0 :     config_ = NULL;
    1165           0 : }
    1166             : 
    1167         803 : LifetimeActor *BgpPeer::deleter() {
    1168         803 :     return deleter_.get();
    1169             : }
    1170             : 
    1171             : //
    1172             : // Check if the given address family has been negotiated with the peer.
    1173             : //
    1174       11330 : bool BgpPeer::IsFamilyNegotiated(Address::Family family) {
    1175             :     // Bail if the family is not configured locally.
    1176       11330 :     if (!LookupFamily(family))
    1177        5335 :         return false;
    1178             : 
    1179             :     // Check if the peer advertised it in his Open message.
    1180             :     uint16_t afi;
    1181             :     uint8_t safi;
    1182        5995 :     tie(afi, safi) = BgpAf::FamilyToAfiSafi(family);
    1183        5995 :     return MpNlriAllowed(afi, safi);
    1184             : }
    1185             : 
    1186             : // Release resources for a peer that is going to be deleted.
    1187         102 : void BgpPeer::PostCloseRelease() {
    1188         102 :     if (index_ != -1) {
    1189         102 :         server_->UnregisterPeer(this);
    1190         102 :         index_ = -1;
    1191             :     }
    1192         102 :     TimerManager::DeleteTimer(keepalive_timer_);
    1193         102 :     TimerManager::DeleteTimer(prefix_limit_idle_timer_);
    1194             : 
    1195         102 :     for (Address::Family family = Address::UNSPEC;
    1196        1122 :             family < Address::NUM_FAMILIES;
    1197        1020 :             family = static_cast<Address::Family>(family + 1)) {
    1198        1020 :         TimerManager::DeleteTimer(eor_send_timer_[family]);
    1199        1020 :         TimerManager::DeleteTimer(eor_receive_timer_[family]);
    1200             :     }
    1201         102 : }
    1202             : 
    1203             : // IsReady
    1204             : //
    1205             : // Check whether this peer is up and ready
    1206             : //
    1207       10540 : bool BgpPeer::IsReady() const {
    1208       10540 :     return state_machine_->get_state() == StateMachine::ESTABLISHED;
    1209             : }
    1210             : 
    1211       51394 : bool BgpPeer::IsXmppPeer() const {
    1212       51394 :     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         496 : uint32_t BgpPeer::bgp_identifier() const {
    1224         496 :     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         404 : void BgpPeer::CustomClose() {
    1252         404 :     ResetCapabilities();
    1253         404 :     keepalive_timer_->Cancel();
    1254             : 
    1255         404 :     for (Address::Family family = Address::UNSPEC;
    1256        4444 :             family < Address::NUM_FAMILIES;
    1257        4040 :             family = static_cast<Address::Family>(family + 1)) {
    1258        4040 :         eor_send_timer_[family]->Cancel();
    1259        4040 :         eor_receive_timer_[family]->Cancel();
    1260             :     }
    1261             : 
    1262         404 :     if (close_manager_->IsInDeleteState())
    1263         165 :         DeleteRTargets(server_->local_autonomous_system());
    1264         404 : }
    1265             : 
    1266             : //
    1267             : // Close this peer by closing all of it's RIBs.
    1268             : //
    1269         804 : void BgpPeer::Close(bool graceful) {
    1270         804 :     send_ready_ = true;
    1271         804 :     if (membership_req_pending_ && !close_manager_->IsMembershipInUse()) {
    1272           2 :         BGP_LOG_PEER(Event, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
    1273             :             BGP_PEER_DIR_NA, "Close procedure deferred");
    1274           2 :         defer_close_ = true;
    1275             : 
    1276             :         // Note down non-graceful closures. Once a close is non-graceful,
    1277             :         // it shall remain as non-graceful.
    1278           2 :         graceful_close_ &= graceful;
    1279           2 :         return;
    1280             :     }
    1281             : 
    1282         802 :     peer_close_->Close(graceful);
    1283             : }
    1284             : 
    1285          96 : IPeerClose *BgpPeer::peer_close() {
    1286          96 :     return peer_close_.get();
    1287             : }
    1288             : 
    1289        5555 : IPeerClose *BgpPeer::peer_close() const {
    1290        5555 :     return peer_close_.get();
    1291             : }
    1292             : 
    1293        5553 : void BgpPeer::UpdateCloseRouteStats(Address::Family family,
    1294             :         const BgpPath *old_path, uint32_t path_flags) const {
    1295        5553 :     peer_close()->UpdateRouteStats(family, old_path, path_flags);
    1296        5551 : }
    1297             : 
    1298        5113 : IPeerDebugStats *BgpPeer::peer_stats() {
    1299        5113 :     return peer_stats_.get();
    1300             : }
    1301             : 
    1302           0 : const IPeerDebugStats *BgpPeer::peer_stats() const {
    1303           0 :     return peer_stats_.get();
    1304             : }
    1305             : 
    1306         166 : void BgpPeer::Clear(int subcode) {
    1307         166 :     CHECK_CONCURRENCY("bgp::Config", "bgp::StateMachine");
    1308         166 :     state_machine_->Shutdown(subcode);
    1309         166 : }
    1310             : 
    1311             : //
    1312             : // Check whether this peer has been marked for deletion from configuration
    1313             : //
    1314        3362 : bool BgpPeer::IsDeleted() const {
    1315        3362 :     return deleter_->IsDeleted();
    1316             : }
    1317             : 
    1318        1009 : bool BgpPeer::IsInGRTimerWaitState() const {
    1319        1009 :     return close_manager_->IsInGRTimerWaitState();
    1320             : }
    1321             : 
    1322        1607 : bool BgpPeer::IsCloseInProgress() const {
    1323        1607 :     CHECK_CONCURRENCY("bgp::Config", "bgp::StateMachine");
    1324             : 
    1325             :     // trigger is set only after defer_close is reset
    1326        1607 :     assert(!(defer_close_ && trigger_.IsSet()));
    1327        4159 :     return defer_close_ || trigger_.IsSet() ||
    1328        1607 :             (close_manager_->IsCloseInProgress() &&
    1329        2552 :              !IsInGRTimerWaitState());
    1330             : }
    1331             : 
    1332       16624 : StateMachine::State BgpPeer::GetState() const {
    1333       16624 :     return state_machine_->get_state();
    1334             : }
    1335             : 
    1336           0 : const string BgpPeer::GetStateName() const {
    1337           0 :     return state_machine_->StateName();
    1338             : }
    1339             : 
    1340         806 : BgpSession *BgpPeer::CreateSession() {
    1341         806 :     if (PrefixLimitIdleTimerRunning())
    1342           0 :         return NULL;
    1343             : 
    1344         806 :     TcpSession *session = server_->session_manager()->CreateSession();
    1345         806 :     if (session == NULL)
    1346           0 :         return NULL;
    1347             : 
    1348             :     // Set valid keys, if any, in the socket.
    1349         806 :     SetSessionSocketAuthKey(session);
    1350             : 
    1351         806 :     BgpSession *bgp_session = static_cast<BgpSession *>(session);
    1352         806 :     BindLocalEndpoint(bgp_session);
    1353         806 :     bgp_session->set_peer(this);
    1354         806 :     return bgp_session;
    1355             : }
    1356             : 
    1357           0 : void BgpPeer::SetAdminState(bool down, int subcode) {
    1358           0 :     CHECK_CONCURRENCY("bgp::Config");
    1359           0 :     if (admin_down_ == down)
    1360           0 :         return;
    1361           0 :     admin_down_ = down;
    1362           0 :     state_machine_->SetAdminState(down, subcode);
    1363           0 :     if (admin_down_) {
    1364           0 :         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         772 : bool BgpPeer::AcceptSession(BgpSession *session) {
    1370         772 :     session->set_peer(this);
    1371             : 
    1372             :     // Set valid keys, if any, in the socket.
    1373         772 :     SetSessionSocketAuthKey(session);
    1374             : 
    1375             :     // Set control dscp, if any
    1376         772 :     SetSessionSocketOptionDscp(session);
    1377             : 
    1378         772 :     return state_machine_->PassiveOpen(session);
    1379             : }
    1380             : 
    1381         692 : 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         692 :     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         692 :     if (close_manager_->IsMembershipInWait())
    1394           0 :         assert(membership_req_pending_ > 0);
    1395         692 :     BgpMembershipManager *membership_mgr = server_->membership_mgr();
    1396         692 :     membership_req_pending_++;
    1397         692 :     membership_mgr->Register(this, table, policy);
    1398             : 
    1399             :     // Start EndOfRib receive timer.
    1400         692 :     StartEndOfRibReceiveTimer(table->family());
    1401         692 : }
    1402             : 
    1403          97 : void BgpPeer::Register(BgpTable *table) {
    1404          97 :     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          97 :     if (close_manager_->IsMembershipInWait())
    1411           0 :         assert(membership_req_pending_ > 0);
    1412          97 :     BgpMembershipManager *membership_mgr = server_->membership_mgr();
    1413          97 :     membership_mgr->RegisterRibIn(this, table);
    1414             : 
    1415             :     // Start EndOfRib receive timer.
    1416          97 :     StartEndOfRibReceiveTimer(table->family());
    1417          97 : }
    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         498 : void BgpPeer::RegisterAllTables() {
    1433         498 :     RoutingInstance *instance = GetRoutingInstance();
    1434             : 
    1435         498 :     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         498 :         (Address::INET)(Address::INETMPLS)(Address::INET6);
    1440        3486 :     BOOST_FOREACH(Address::Family family, family_list) {
    1441        1494 :         if (!IsFamilyNegotiated(family))
    1442        1106 :             continue;
    1443         388 :         BgpTable *table = instance->GetTable(family);
    1444         776 :         BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_TRACE,
    1445             :                            table, "Register peer with the table");
    1446         388 :         Register(table, BuildRibExportPolicy(family));
    1447             :     }
    1448             : 
    1449             : 
    1450         899 :     if (((router_type_ == "bgpaas-client") ||
    1451         996 :         (router_type_ == "bgpaas-server")) &&
    1452          97 :         (instance->routing_instance_vxlan() != "")) {
    1453          97 :         RoutingInstanceMgr *mgr = server()->routing_instance_mgr();
    1454          97 :         if (mgr != nullptr) {
    1455             :             RoutingInstance *vxlan_ri =
    1456          97 :                 mgr->GetRoutingInstance(instance->routing_instance_vxlan());
    1457          97 :             if (vxlan_ri != nullptr) {
    1458          97 :                 BgpTable *table = vxlan_ri->GetTable(Address::EVPN);
    1459         194 :                 BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_TRACE,
    1460             :                     table, "Register ribin for peer with the table");
    1461          97 :                 Register(table);
    1462             :             }
    1463             :         }
    1464             :     }
    1465             : 
    1466         498 :     vpn_tables_registered_ = false;
    1467         498 :     if (!IsFamilyNegotiated(Address::RTARGET)) {
    1468         498 :         RegisterToVpnTables();
    1469         498 :         return;
    1470             :     }
    1471             : 
    1472           0 :     Address::Family family = Address::RTARGET;
    1473           0 :     BgpTable *table = instance->GetTable(family);
    1474           0 :     BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_DEBUG, BGP_LOG_FLAG_TRACE,
    1475             :         table, "Register peer with the table");
    1476           0 :     Register(table, BuildRibExportPolicy(family));
    1477             : 
    1478             :     vector<Address::Family> vpn_family_list = list_of
    1479           0 :         (Address::INETVPN)(Address::INET6VPN)(Address::ERMVPN)(Address::EVPN)
    1480           0 :         (Address::MVPN);
    1481           0 :     BOOST_FOREACH(Address::Family vpn_family, vpn_family_list) {
    1482           0 :         if (!IsFamilyNegotiated(vpn_family))
    1483           0 :             continue;
    1484           0 :         BgpTable *table = instance->GetTable(vpn_family);
    1485           0 :         BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_TRACE,
    1486             :             table, "Register ribin for peer with the table");
    1487           0 :         Register(table);
    1488             :     }
    1489         498 : }
    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        1055 : void BgpPeer::SendOpen(TcpSession *session) {
    1503        1055 :     BgpProto::OpenMessage openmsg;
    1504        1055 :     openmsg.as_num = local_as_ > 0xffff ? AS_TRANS : local_as_;
    1505        1055 :     openmsg.holdtime = state_machine_->GetConfiguredHoldTime();
    1506        1055 :     openmsg.identifier = ntohl(local_bgp_id_);
    1507             :     BgpProto::OpenMessage::OptParam *opt_param =
    1508        1055 :         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        1073 :     };
    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        1056 :         (supported_families_[8], cap_mp[8]);
    1541             : 
    1542             :     // Add capabilities for configured address families.
    1543       20045 :     BOOST_FOREACH(const FamilyToCapabilityMap::value_type &val,
    1544             :         family_to_cap_map) {
    1545        9495 :         if (!LookupFamily(val.first))
    1546        7779 :             continue;
    1547             :         BgpProto::OpenMessage::Capability *cap =
    1548             :             new BgpProto::OpenMessage::Capability(
    1549        1716 :                 BgpProto::OpenMessage::Capability::MpExtension, val.second, 4);
    1550        1716 :         opt_param->capabilities.push_back(cap);
    1551             :     }
    1552             : 
    1553        1055 :     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        1055 :     peer_close_->AddGRCapabilities(opt_param);
    1562        1055 :     peer_close_->AddLLGRCapabilities(opt_param);
    1563             : 
    1564        1055 :     if (opt_param->capabilities.size()) {
    1565        1055 :         openmsg.opt_params.push_back(opt_param);
    1566             :     } else {
    1567           0 :         delete opt_param;
    1568             :     }
    1569             :     uint8_t data[256];
    1570        1055 :     int result = BgpProto::Encode(&openmsg, data, sizeof(data));
    1571        1055 :     assert(result > BgpProto::kMinMessageSize);
    1572        1055 :     BGP_LOG_PEER(Message, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
    1573             :                  BGP_PEER_DIR_OUT, "Open "  << openmsg.ToString());
    1574        1055 :     session->Send(data, result, NULL);
    1575        1055 :     inc_tx_open();
    1576        1055 : }
    1577             : 
    1578         498 : void BgpPeer::SendKeepalive(bool from_timer) {
    1579         498 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
    1580             : 
    1581             :     // Bail if there's no session for the peer anymore.
    1582         498 :     if (!session_)
    1583           0 :         return;
    1584             : 
    1585         498 :     BgpProto::Keepalive msg;
    1586             :     uint8_t data[BgpProto::kMinMessageSize];
    1587         498 :     int result = BgpProto::Encode(&msg, data, sizeof(data));
    1588         497 :     assert(result == BgpProto::kMinMessageSize);
    1589         497 :     SandeshLevel::type log_level = from_timer ? Sandesh::LoggingUtLevel() :
    1590         497 :                                                 SandeshLevel::SYS_INFO;
    1591         497 :     BGP_LOG_PEER(Message, this, log_level, BGP_LOG_FLAG_SYSLOG,
    1592             :                  BGP_PEER_DIR_OUT, "Keepalive");
    1593         498 :     send_ready_ = session_->Send(data, result, NULL);
    1594         498 :     inc_tx_keepalive();
    1595         498 : }
    1596             : 
    1597        4346 : static bool SkipUpdateSend() {
    1598             :     static bool init_;
    1599             :     static bool skip_;
    1600             : 
    1601        4346 :     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         234 : BgpPeer::OriginOverride::OriginOverride(
    1610         234 :                 const BgpNeighborConfig::OriginOverrideConfig &config)
    1611         234 :         : origin_override(config.origin_override),
    1612         234 :         origin(BgpAttr::OriginFromString(config.origin)) {
    1613         234 : }
    1614             : 
    1615         132 : bool BgpPeer::OriginOverride::operator!=(const OriginOverride &rhs) const {
    1616         132 :     if (origin_override != rhs.origin_override) {
    1617           0 :         return true;
    1618             :     }
    1619             : 
    1620             :     // compare origin only if override is set
    1621         132 :     if (origin_override && origin != rhs.origin) {
    1622           0 :         return true;
    1623             :     }
    1624         132 :     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        4615 : bool BgpPeer::SendUpdate(const uint8_t *msg, size_t msgsize,
    1633             :     const string *msg_str) {
    1634        4615 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
    1635        4615 :     bool send_ready = true;
    1636        4615 :     if (buffer_.size() + msgsize > buffer_capacity_) {
    1637           0 :         send_ready = FlushUpdateUnlocked();
    1638           0 :         assert(buffer_.empty());
    1639             :     }
    1640        4615 :     buffer_.insert(buffer_.end(), msg, msg + msgsize);
    1641        4615 :     inc_tx_update();
    1642        4615 :     return send_ready;
    1643        4615 : }
    1644             : 
    1645        4495 : bool BgpPeer::FlushUpdateUnlocked() {
    1646             :     // Bail if the update buffer is empty.
    1647        4495 :     if (buffer_.empty())
    1648         149 :         return true;
    1649             : 
    1650             :     // Bail if there's no session for the peer anymore.
    1651        4346 :     if (!session_) {
    1652           0 :         buffer_.clear();
    1653           0 :         return true;
    1654             :     }
    1655             : 
    1656        4346 :     if (!SkipUpdateSend()) {
    1657        4346 :         send_ready_ = session_->Send(buffer_.data(), buffer_.size(), NULL);
    1658        4346 :         buffer_.clear();
    1659        4346 :         if (send_ready_) {
    1660        4346 :             StartKeepaliveTimerUnlocked();
    1661             :         } else {
    1662           0 :             StopKeepaliveTimerUnlocked();
    1663             :         }
    1664             :     } else {
    1665           0 :         send_ready_ = true;
    1666             :     }
    1667             : 
    1668        4346 :     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        4346 :     return send_ready_;
    1673             : }
    1674             : 
    1675        4492 : bool BgpPeer::FlushUpdate() {
    1676        4492 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
    1677        8990 :     return FlushUpdateUnlocked();
    1678        4495 : }
    1679             : 
    1680         517 : bool BgpPeer::notification() const {
    1681         517 :     return peer_close_->gr_params().notification();
    1682             : }
    1683             : 
    1684             : // Check if GR Helper mode sould be attempted.
    1685         804 : bool BgpPeer::AttemptGRHelperMode(int code, int subcode) const {
    1686         804 :     if (!code)
    1687         135 :         return true;
    1688             : 
    1689         669 :     if (code == BgpProto::Notification::Cease &&
    1690         502 :             (subcode == BgpProto::Notification::HardReset ||
    1691             :              subcode == BgpProto::Notification::PeerDeconfigured)) {
    1692         152 :         return false;
    1693             :     }
    1694             : 
    1695             :     // If Peer supports Notification (N) bit, then attempt GR-Helper for all
    1696             :     // other notifications, not otherwise.
    1697         517 :     return notification();
    1698             : }
    1699             : 
    1700         485 : void BgpPeer::SendNotification(BgpSession *session,
    1701             :         int code, int subcode, const string &data) {
    1702         485 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
    1703         485 :     session->SendNotification(code, subcode, data);
    1704         485 :     state_machine_->set_last_notification_out(code, subcode, data);
    1705         485 :     inc_tx_notification();
    1706         485 : }
    1707             : 
    1708         498 : bool BgpPeer::SetCapabilities(const BgpProto::OpenMessage *msg) {
    1709         498 :     peer_bgp_id_ = htonl(msg->identifier);
    1710         498 :     capabilities_.clear();
    1711         498 :     vector<BgpProto::OpenMessage::OptParam *>::const_iterator it;
    1712         996 :     for (it = msg->opt_params.begin(); it < msg->opt_params.end(); ++it) {
    1713         498 :         capabilities_.insert(capabilities_.end(), (*it)->capabilities.begin(),
    1714         498 :                              (*it)->capabilities.end());
    1715         498 :         (*it)->capabilities.clear();
    1716             :     }
    1717             : 
    1718         498 :     as4_supported_ = false;
    1719         498 :     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         996 :     BgpPeerInfoData peer_info;
    1729         498 :     peer_info.set_name(ToUVEKey());
    1730         498 :     peer_info.set_peer_id(peer_bgp_id_);
    1731             : 
    1732         498 :     vector<string> families;
    1733         498 :     vector<BgpProto::OpenMessage::Capability *>::iterator cap_it;
    1734        2186 :     for (cap_it = capabilities_.begin(); cap_it < capabilities_.end();
    1735        1688 :          ++cap_it) {
    1736        1688 :         if ((*cap_it)->code != BgpProto::OpenMessage::Capability::MpExtension)
    1737         996 :             continue;
    1738         692 :         uint8_t *data = (*cap_it)->capability.data();
    1739         692 :         uint16_t afi = get_value(data, 2);
    1740         692 :         uint8_t safi = get_value(data + 3, 1);
    1741         692 :         Address::Family family = BgpAf::AfiSafiToFamily(afi, safi);
    1742         692 :         if (family == Address::UNSPEC) {
    1743           0 :             families.push_back(BgpAf::ToString(afi, safi));
    1744             :         } else {
    1745         692 :             families.push_back(Address::FamilyToString(family));
    1746             :         }
    1747             :     }
    1748         498 :     peer_info.set_families(families);
    1749             : 
    1750         498 :     negotiated_families_.clear();
    1751        5478 :     for (int idx = Address::UNSPEC; idx < Address::NUM_FAMILIES; ++idx) {
    1752        4980 :         if (!family_attributes_list_[idx])
    1753        4288 :             continue;
    1754         692 :         Address::Family family = static_cast<Address::Family>(idx);
    1755             :         uint16_t afi;
    1756             :         uint8_t safi;
    1757         692 :         tie(afi, safi) = BgpAf::FamilyToAfiSafi(family);
    1758         692 :         if (!MpNlriAllowed(afi, safi))
    1759           0 :             continue;
    1760         692 :         negotiated_families_.push_back(Address::FamilyToString(family));
    1761             :     }
    1762         498 :     sort(negotiated_families_.begin(), negotiated_families_.end());
    1763         498 :     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         498 :     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         498 :     return true;
    1774         498 : }
    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         404 : void BgpPeer::ResetCapabilities() {
    1782         404 :     STLDeleteValues(&capabilities_);
    1783         808 :     BgpPeerInfoData peer_info;
    1784         404 :     peer_info.set_name(ToUVEKey());
    1785         404 :     vector<string> families = vector<string>();
    1786         404 :     peer_info.set_families(families);
    1787         404 :     vector<string> negotiated_families = vector<string>();
    1788         404 :     peer_info.set_negotiated_families(negotiated_families);
    1789         404 :     peer_info.set_graceful_restart_families(vector<string>());
    1790         404 :     BGPPeerInfoSend(peer_info);
    1791         404 : }
    1792             : 
    1793        6686 : bool BgpPeer::MpNlriAllowed(uint16_t afi, uint8_t safi) {
    1794        6686 :     vector<BgpProto::OpenMessage::Capability *>::iterator it;
    1795        8352 :     for (it = capabilities_.begin(); it < capabilities_.end(); ++it) {
    1796        8353 :         if ((*it)->code != BgpProto::OpenMessage::Capability::MpExtension)
    1797           0 :             continue;
    1798        8353 :         uint8_t *data = (*it)->capability.data();
    1799        8353 :         uint16_t af_value = get_value(data, 2);
    1800        8353 :         uint8_t safi_value = get_value(data + 3, 1);
    1801        8353 :         if (afi == af_value && safi == safi_value) {
    1802        6687 :             return true;
    1803             :         }
    1804             :     }
    1805           0 :     return false;
    1806             : }
    1807             : 
    1808        7530 : bool BgpPeer::Is4ByteAsSupported() const {
    1809        7530 :     return as4_supported_;
    1810             : }
    1811             : 
    1812             : template <typename TableT, typename PrefixT>
    1813        4615 : void BgpPeer::ProcessNlri(Address::Family family, DBRequest::DBOperation oper,
    1814             :     const BgpMpNlri *nlri, BgpAttrPtr attr, uint32_t flags) {
    1815        4615 :     TableT *table = static_cast<TableT *>(rtinstance_->GetTable(family));
    1816        4615 :     assert(table);
    1817             : 
    1818        9273 :     for (vector<BgpProtoPrefix *>::const_iterator it = nlri->nlri.begin();
    1819        9273 :          it != nlri->nlri.end(); ++it) {
    1820        4658 :         PrefixT prefix;
    1821        4658 :         BgpAttrPtr new_attr(attr);
    1822        4658 :         uint32_t label = 0;
    1823        4658 :         uint32_t l3_label = 0;
    1824        7853 :         int result = PrefixT::FromProtoPrefix(server_, **it,
    1825        3195 :             (oper == DBRequest::DB_ENTRY_ADD_CHANGE ? attr.get() : NULL),
    1826             :             family, &prefix, &new_attr, &label, &l3_label);
    1827        4658 :         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        4658 :         DBRequest req;
    1836        4658 :         req.oper = oper;
    1837        4658 :         if (oper == DBRequest::DB_ENTRY_ADD_CHANGE) {
    1838        3195 :             req.data.reset(new typename TableT::RequestData(
    1839             :                 new_attr, flags, label, l3_label, 0));
    1840             :         }
    1841        4658 :         req.key.reset(new typename TableT::RequestKey(prefix, this));
    1842        4658 :         table->Enqueue(&req);
    1843             :     }
    1844        4615 : }
    1845             : 
    1846             : template <typename PrefixT>
    1847         704 : void BgpPeer::ProcessNlriBgpaas(Address::Family family, DBRequest::DBOperation oper,
    1848             :     const BgpMpNlri *nlri, BgpAttrPtr attr, uint32_t flags) {
    1849             : 
    1850        1408 :     for (vector<BgpProtoPrefix *>::const_iterator it = nlri->nlri.begin();
    1851        1408 :          it != nlri->nlri.end(); ++it) {
    1852         704 :         PrefixT prefix;
    1853         704 :         BgpAttrPtr new_attr(attr);
    1854         704 :         uint32_t label = 0;
    1855         704 :         uint32_t l3_label = 0;
    1856        1120 :         int result = PrefixT::FromProtoPrefix(server_, **it,
    1857         416 :             (oper == DBRequest::DB_ENTRY_ADD_CHANGE ? attr.get() : NULL),
    1858             :             family, &prefix, &new_attr, &label, &l3_label);
    1859         704 :         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         704 :         ProcessBgpaas(oper, prefix.addr(), prefix.prefixlen(), new_attr, flags);
    1868             :     }
    1869         704 : }
    1870             : 
    1871         704 : void BgpPeer::ProcessBgpaas(DBRequest::DBOperation oper,
    1872             :     IpAddress addr, uint8_t addr_len, BgpAttrPtr attr, uint32_t flags) {
    1873             : 
    1874         704 :     if (rtinstance_->routing_instance_vxlan() == "") {
    1875           0 :         return;
    1876             :     }
    1877         704 :     RoutingInstanceMgr *mgr = server()->routing_instance_mgr();
    1878         704 :     if (mgr == nullptr) {
    1879           0 :         return;
    1880             :     }
    1881             :     RoutingInstance *vxlan_ri =
    1882         704 :         mgr->GetRoutingInstance(rtinstance_->routing_instance_vxlan());
    1883         704 :     if (vxlan_ri == nullptr) {
    1884           0 :         return;
    1885             :     }
    1886         704 :     EvpnTable *table = static_cast<EvpnTable *>(vxlan_ri->GetTable(Address::EVPN));
    1887         704 :     EvpnPrefix prefix_evpn(RouteDistinguisher::kZeroRd, addr, addr_len);
    1888             : 
    1889         704 :     DBRequest req;
    1890         704 :     req.oper = oper;
    1891         704 :     if (oper == DBRequest::DB_ENTRY_ADD_CHANGE) {
    1892         416 :         req.data.reset(new EvpnTable::RequestData(attr, flags, 0, 0, 0));
    1893             :     }
    1894             :     else {
    1895         288 :         req.data.reset(NULL);
    1896             :     }
    1897         704 :     req.key.reset(new EvpnTable::RequestKey(prefix_evpn, this));
    1898         704 :     table->Enqueue(&req);
    1899         704 : }
    1900             : 
    1901        3195 : uint32_t BgpPeer::GetPathFlags(Address::Family family,
    1902             :     const BgpAttr *attr) const {
    1903        3195 :     uint32_t flags = resolve_paths_ ? BgpPath::ResolveNexthop : 0;
    1904             : 
    1905             :     // Check for OriginatorId loop in case we are an RR client.
    1906        5672 :     if (peer_type_ == BgpProto::IBGP &&
    1907        2477 :         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        3195 :     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        3195 :     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        4631 :     if ((PeerType() == BgpProto::EBGP) &&
    1923        2154 :           ((attr->as_path() && !attr->as_path()->path().AsLeftMostMatch(
    1924        1436 :           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        3195 :     uint8_t max_loop_count = family_attributes_list_[family]->loop_count;
    1931        3195 :     if (attr->IsAsPathLoop(local_as_, max_loop_count))
    1932           0 :         flags |= BgpPath::AsPathLooped;
    1933             : 
    1934        3195 :     return flags;
    1935             : }
    1936             : 
    1937        5303 : uint32_t BgpPeer::GetLocalPrefFromMed(uint32_t med) const {
    1938        5303 :     if (peer_type_ != BgpProto::EBGP)
    1939        3931 :         return 0;
    1940        1372 :     if (!peer_is_control_node_)
    1941        1372 :         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        5303 : void BgpPeer::ProcessUpdate(const BgpProto::Update *msg, size_t msgsize) {
    1952        5303 :     BgpAttrPtr attr = server_->attr_db()->Locate(msg->path_attributes);
    1953             : 
    1954        5303 :     uint32_t local_pref = GetLocalPrefFromMed(attr->med());
    1955        5303 :     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        5303 :     if (origin_override_.origin_override) {
    1962           0 :         attr = server_->attr_db()->ReplaceOriginAndLocate(attr.get(),
    1963           0 :                                                        origin_override_.origin);
    1964             :     }
    1965             : 
    1966        9708 :     if ((router_type_ == "bgpaas-client") ||
    1967        4405 :         (router_type_ == "bgpaas-server")) {
    1968        2694 :         attr = server_->attr_db()->ReplaceSubProtocolAndLocate(attr.get(),
    1969        2694 :                              MatchProtocolToString(MatchProtocol::BGPaaS));
    1970             :     }
    1971             : 
    1972        5303 :     uint32_t reach_count = 0, unreach_count = 0;
    1973        5303 :     RoutingInstance *instance = GetRoutingInstance();
    1974        5303 :     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        5303 :     for (vector<BgpAttribute *>::const_iterator ait =
    2037        5303 :             msg->path_attributes.begin();
    2038       22072 :             ait != msg->path_attributes.end(); ++ait) {
    2039             :         DBRequest::DBOperation oper;
    2040       17458 :         if ((*ait)->code == BgpAttribute::MPReachNlri) {
    2041        3195 :             oper = DBRequest::DB_ENTRY_ADD_CHANGE;
    2042       14263 :         } else if ((*ait)->code == BgpAttribute::MPUnreachNlri) {
    2043        2108 :             oper = DBRequest::DB_ENTRY_DELETE;
    2044             :         } else {
    2045       12154 :             continue;
    2046             :         }
    2047             : 
    2048        5303 :         BgpMpNlri *nlri = static_cast<BgpMpNlri *>(*ait);
    2049        5303 :         assert(nlri);
    2050        5303 :         if (oper == DBRequest::DB_ENTRY_ADD_CHANGE) {
    2051        3195 :             reach_count += nlri->nlri.size();
    2052             :         } else {
    2053        2108 :             unreach_count += nlri->nlri.size();
    2054             :         }
    2055             : 
    2056        5303 :         Address::Family family = BgpAf::AfiSafiToFamily(nlri->afi, nlri->safi);
    2057        5303 :         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        5303 :         if (oper == DBRequest::DB_ENTRY_DELETE && nlri->nlri.empty()) {
    2067         688 :             inc_rx_end_of_rib();
    2068         688 :             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         688 :             ReceiveEndOfRIB(family, msgsize);
    2074         688 :             return;
    2075             :         }
    2076             : 
    2077        4615 :         uint32_t flags = 0;
    2078        4615 :         if ((*ait)->code == BgpAttribute::MPReachNlri) {
    2079        3195 :             flags = GetPathFlags(family, attr.get());
    2080        3195 :             attr = GetMpNlriNexthop(nlri, attr);
    2081             :         }
    2082             : 
    2083        4615 :         switch (family) {
    2084        1600 :         case Address::INET:
    2085             :         case Address::INETMPLS:
    2086        1600 :             ProcessNlri<InetTable, Ip4Prefix>(
    2087             :                 family, oper, nlri, attr, flags);
    2088        2880 :             if ((router_type_ == "bgpaas-client") ||
    2089        1280 :                 (router_type_ == "bgpaas-server")) {
    2090         320 :                 ProcessNlriBgpaas<Ip4Prefix>(
    2091             :                     family, oper, nlri, attr, flags);
    2092             :             }
    2093        1600 :             break;
    2094           0 :         case Address::INETVPN:
    2095           0 :             ProcessNlri<InetVpnTable, InetVpnPrefix>(
    2096             :                 family, oper, nlri, attr, flags);
    2097           0 :             break;
    2098        1084 :         case Address::INET6:
    2099        1084 :             ProcessNlri<Inet6Table, Inet6Prefix>(
    2100             :                 family, oper, nlri, attr, flags);
    2101        1784 :             if ((router_type_ == "bgpaas-client") ||
    2102         700 :                 (router_type_ == "bgpaas-server")) {
    2103         384 :                 ProcessNlriBgpaas<Inet6Prefix>(
    2104             :                     family, oper, nlri, attr, flags);
    2105             :             }
    2106        1084 :             break;
    2107           0 :         case Address::INET6VPN:
    2108           0 :             ProcessNlri<Inet6VpnTable, Inet6VpnPrefix>(
    2109             :                 family, oper, nlri, attr, flags);
    2110           0 :             break;
    2111        1931 :         case Address::EVPN:
    2112        1931 :             ProcessNlri<EvpnTable, EvpnPrefix>(
    2113             :                 family, oper, nlri, attr, flags);
    2114        1931 :             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           0 :         case Address::RTARGET:
    2124           0 :             ProcessNlri<RTargetTable, RTargetPrefix>(
    2125             :                 family, oper, nlri, attr, flags);
    2126           0 :             break;
    2127           0 :         default:
    2128           0 :             break;
    2129             :         }
    2130             :     }
    2131             : 
    2132        4615 :     inc_rx_route_reach(reach_count);
    2133        4615 :     inc_rx_route_unreach(unreach_count);
    2134        4615 :     if (Sandesh::LoggingLevel() >= Sandesh::LoggingUtLevel()) {
    2135        4615 :         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        5303 : }
    2141        8038 : const std::vector<std::string> BgpPeer::GetDefaultTunnelEncap(
    2142             :     const Address::Family family) const {
    2143        8038 :     if (family_attributes_list_[family] == NULL)
    2144        2787 :         return std::vector<std::string>();
    2145        5250 :     return family_attributes_list_[family]->default_tunnel_encap_list;
    2146             : }
    2147             : 
    2148        8040 : void BgpPeer::ProcessPathTunnelEncapsulation(const BgpPath *path, BgpAttr *attr,
    2149             :                                              ExtCommunityDB *extcomm_db,
    2150             :                                              const BgpTable *table) const {
    2151        8040 :     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        8016 : }
    2180             : 
    2181             : 
    2182       10744 : void BgpPeer::UpdatePrimaryPathCount(int count, Address::Family family) const {
    2183       10744 :     primary_path_count_ += count;
    2184       10761 :     if (family == Address::UNSPEC)
    2185           0 :         return;
    2186       10761 :     family_primary_path_count_[family] += count;
    2187       10763 :     uint32_t limit = 0;
    2188       10763 :     if (family_attributes_list_[family])
    2189        9217 :         limit = family_attributes_list_[family]->prefix_limit;
    2190       10745 :     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          64 : void BgpPeer::StopPrefixLimitIdleTimer() {
    2201          64 :     prefix_limit_idle_timer_->Cancel();
    2202          64 : }
    2203             : 
    2204        1609 : bool BgpPeer::PrefixLimitIdleTimerRunning() const {
    2205        1609 :     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         498 : void BgpPeer::RegisterToVpnTables() {
    2225         498 :     CHECK_CONCURRENCY("bgp::StateMachine", "bgp::RTFilter", "bgp::Config");
    2226             : 
    2227         498 :     if (vpn_tables_registered_)
    2228           0 :         return;
    2229         498 :     vpn_tables_registered_ = true;
    2230             : 
    2231         498 :     RoutingInstance *instance = GetRoutingInstance();
    2232             :     vector<Address::Family> vpn_family_list = list_of
    2233         498 :         (Address::INETVPN)(Address::INET6VPN)(Address::ERMVPN)(Address::EVPN)
    2234         498 :         (Address::MVPN);
    2235        5478 :     BOOST_FOREACH(Address::Family vpn_family, vpn_family_list) {
    2236        2490 :         if (!IsFamilyNegotiated(vpn_family))
    2237        2186 :             continue;
    2238         304 :         BgpTable *table = instance->GetTable(vpn_family);
    2239         608 :         BGP_LOG_PEER_TABLE(this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_TRACE,
    2240             :             table, "Register peer with the table");
    2241         304 :         Register(table, BuildRibExportPolicy(vpn_family));
    2242             :     }
    2243         498 : }
    2244             : 
    2245         789 : void BgpPeer::StartEndOfRibReceiveTimer(Address::Family family) {
    2246         789 :     uint32_t timeout = GetEndOfRibReceiveTime(family);
    2247             : 
    2248         789 :     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         789 :     eor_receive_timer_[family]->Start(timeout * 1000,
    2254             :         boost::bind(&BgpPeer::EndOfRibReceiveTimerExpired, this, family),
    2255             :         boost::bind(&BgpPeer::EndOfRibTimerErrorHandler, this, _1, _2));
    2256         789 : }
    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          64 : bool BgpPeer::EndOfRibReceiveTimerExpired(Address::Family family) {
    2265          64 :     if (family == Address::RTARGET)
    2266           0 :         RegisterToVpnTables();
    2267             : 
    2268             :     // Fake reception of EoRs to exit from GR states and sweep all stale routes.
    2269          64 :     close_manager_->ProcessEORMarkerReceived(family);
    2270          64 :     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        4844 : void BgpPeer::StartKeepaliveTimerUnlocked() {
    2286        4844 :     int keepalive_time_msecs = state_machine_->keepalive_time_msecs();
    2287        4844 :     if (keepalive_time_msecs <= 0)
    2288           0 :         return;
    2289             : 
    2290        4844 :     keepalive_timer_->Start(keepalive_time_msecs,
    2291             :         boost::bind(&BgpPeer::KeepaliveTimerExpired, this),
    2292             :         boost::bind(&BgpPeer::KeepaliveTimerErrorHandler, this, _1, _2));
    2293             : }
    2294             : 
    2295         498 : void BgpPeer::StartKeepaliveTimer() {
    2296         498 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
    2297         498 :     if (session_ && send_ready_)
    2298         498 :         StartKeepaliveTimerUnlocked();
    2299         498 : }
    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         498 : void BgpPeer::set_session(BgpSession *session) {
    2320         498 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
    2321         498 :     assert(session_ == NULL);
    2322         498 :     session_ = session;
    2323         498 : }
    2324             : 
    2325         906 : void BgpPeer::clear_session() {
    2326         906 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
    2327         906 :     if (session_) {
    2328         498 :         session_->clear_peer();
    2329         498 :         session_->set_observer(NULL);
    2330         498 :         session_->Close();
    2331             :     }
    2332         906 :     session_ = NULL;
    2333         906 : }
    2334             : 
    2335        3299 : BgpSession *BgpPeer::session() {
    2336        3299 :     return session_;
    2337             : }
    2338             : 
    2339        6341 : string BgpPeer::BytesToHexString(const u_int8_t *msg, size_t size) {
    2340        6341 :     ostringstream out;
    2341             :     char buf[4];
    2342             : 
    2343      471268 :     for (size_t i = 0; i < size; i ++) {
    2344      464924 :         if (!(i % 32)) out << "\n";
    2345      464925 :         if (!(i %  4)) out << " 0x";
    2346      464919 :         snprintf(buf, sizeof(buf), "%02X", msg[i]);
    2347      464919 :         out << buf;
    2348             :     }
    2349             : 
    2350        6344 :     out << "\n";
    2351             : 
    2352       12684 :     return out.str();
    2353        6342 : }
    2354             : 
    2355        6840 : bool BgpPeer::ReceiveMsg(BgpSession *session, const u_int8_t *msg,
    2356             :                          size_t size) {
    2357        6840 :     ParseErrorContext ec;
    2358       13680 :     BgpProto::BgpMessage *minfo = BgpProto::Decode(msg, size, &ec,
    2359        6840 :                                                    Is4ByteAsSupported());
    2360             : 
    2361        6840 :     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        6840 :     if (minfo->type != BgpProto::KEEPALIVE)
    2372        6342 :         BGP_TRACE_PEER_PACKET(this, msg, size, SandeshLevel::SYS_WARN); //Sandesh::LoggingUtLevel()
    2373             : 
    2374        6840 :     state_machine_->OnMessage(session, minfo, size);
    2375        6840 :     return true;
    2376        6840 : }
    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        3195 : BgpAttrPtr BgpPeer::GetMpNlriNexthop(BgpMpNlri *nlri, BgpAttrPtr attr) {
    2384        3195 :     bool update_nh = false;
    2385        3195 :     IpAddress addr;
    2386             : 
    2387        3195 :     if (nlri->afi == BgpAf::IPv4) {
    2388         992 :         if (nlri->safi == BgpAf::Mpls || nlri->safi == BgpAf::Unicast ||
    2389           0 :             nlri->safi == BgpAf::RTarget || nlri->safi == BgpAf::MVpn) {
    2390         992 :             Ip4Address::bytes_type bt = { { 0 } };
    2391        1984 :             copy(nlri->nexthop.begin(),
    2392         992 :                 nlri->nexthop.begin() + sizeof(bt), bt.begin());
    2393         992 :             addr = Ip4Address(bt);
    2394         992 :             update_nh = true;
    2395         992 :         } else if (nlri->safi == BgpAf::Vpn) {
    2396           0 :             Ip4Address::bytes_type bt = { { 0 } };
    2397           0 :             size_t rdsize = RouteDistinguisher::kSize;
    2398           0 :             copy(nlri->nexthop.begin() + rdsize,
    2399           0 :                 nlri->nexthop.begin() + rdsize + sizeof(bt), bt.begin());
    2400           0 :             addr = Ip4Address(bt);
    2401           0 :             update_nh = true;
    2402             :         }
    2403        2203 :     } else if (nlri->afi == BgpAf::L2Vpn) {
    2404        1501 :         if (nlri->safi == BgpAf::EVpn) {
    2405        1501 :             Ip4Address::bytes_type bt = { { 0 } };
    2406        3002 :             copy(nlri->nexthop.begin(),
    2407        1501 :                 nlri->nexthop.begin() + sizeof(bt), bt.begin());
    2408        1501 :             addr = Ip4Address(bt);
    2409        1501 :             update_nh = true;
    2410             :         }
    2411         702 :     } else if (nlri->afi == BgpAf::IPv6) {
    2412         702 :         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         702 :             for (int idx = 0; idx < 2; ++idx) {
    2420         702 :                 Ip6Address::bytes_type bt = { { 0 } };
    2421         702 :                 if ((idx + 1) * sizeof(bt) > nlri->nexthop.size())
    2422         702 :                     break;
    2423        1404 :                 copy(nlri->nexthop.begin() + idx * sizeof(bt),
    2424         702 :                     nlri->nexthop.begin() + (idx + 1) * sizeof(bt), bt.begin());
    2425         702 :                 Ip6Address v6_addr(bt);
    2426         702 :                 if (v6_addr.is_v4_mapped()) {
    2427         590 :                     addr = Address::V4FromV4MappedV6(v6_addr);
    2428         590 :                     update_nh = true;
    2429         590 :                     break;
    2430             :                 }
    2431         112 :                 if (!v6_addr.is_link_local()) {
    2432         112 :                     addr = v6_addr;
    2433         112 :                     update_nh = true;
    2434         112 :                     break;
    2435             :                 }
    2436             :             }
    2437           0 :         } else if (nlri->safi == BgpAf::Vpn) {
    2438           0 :             Ip6Address::bytes_type bt = { { 0 } };
    2439           0 :             size_t rdsize = RouteDistinguisher::kSize;
    2440           0 :             copy(nlri->nexthop.begin() + rdsize,
    2441           0 :                 nlri->nexthop.begin() + rdsize + sizeof(bt), bt.begin());
    2442           0 :             Ip6Address v6_addr(bt);
    2443           0 :             if (v6_addr.is_v4_mapped()) {
    2444           0 :                 addr = Address::V4FromV4MappedV6(v6_addr);
    2445           0 :                 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        3195 :     if (update_nh) {
    2453        3195 :         attr = server_->attr_db()->ReplaceNexthopAndLocate(attr.get(), addr);
    2454             :     }
    2455        6390 :     return attr;
    2456             : }
    2457             : 
    2458         102 : void BgpPeer::ManagedDelete() {
    2459         102 :     if (deleter_->IsDeleted())
    2460           0 :         return;
    2461         102 :     BGP_LOG_PEER(Config, this, SandeshLevel::SYS_INFO, BGP_LOG_FLAG_ALL,
    2462             :                  BGP_PEER_DIR_NA, "Received request for deletion");
    2463         102 :     if (IsRouterTypeBGPaaS()) {
    2464          34 :         server()->increment_deleting_bgpaas_count();
    2465             :     } else {
    2466          68 :         server()->increment_deleting_count();
    2467             :     }
    2468         102 :     deleter_->Delete();
    2469             : }
    2470             : 
    2471         336 : void BgpPeer::RetryDelete() {
    2472         336 :     if (!deleter_->IsDeleted())
    2473         132 :         return;
    2474         204 :     deleter_->RetryDelete();
    2475             : }
    2476             : 
    2477        4536 : int BgpPeer::GetTaskInstance() const {
    2478        4536 :     return index_ % TaskScheduler::GetInstance()->HardwareThreadCount();
    2479             : }
    2480             : 
    2481        6342 : void BgpPeer::SetDataCollectionKey(BgpPeerInfo *peer_info) const {
    2482        6342 :     if (rtinstance_) {
    2483        6342 :         peer_info->set_domain(rtinstance_->name());
    2484             :     } else {
    2485           0 :         peer_info->set_domain(BgpConfigManager::kMasterInstance);
    2486             :     }
    2487             : 
    2488        6342 :     peer_info->set_ip_address(peer_key_.endpoint.address().to_string());
    2489        6341 : }
    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         662 : void BgpPeer::inc_rx_open() {
    2658         662 :     peer_stats_->proto_stats_[0].open++;
    2659         662 : }
    2660             : 
    2661        1055 : void BgpPeer::inc_tx_open() {
    2662        1055 :     peer_stats_->proto_stats_[1].open++;
    2663        1055 : }
    2664             : 
    2665         498 : void BgpPeer::inc_rx_keepalive() {
    2666         498 :     peer_stats_->proto_stats_[0].keepalive++;
    2667         498 : }
    2668             : 
    2669           0 : uint64_t BgpPeer::get_rx_keepalive() const {
    2670           0 :     return peer_stats_->proto_stats_[0].keepalive;
    2671             : }
    2672             : 
    2673         498 : void BgpPeer::inc_tx_keepalive() {
    2674         498 :     peer_stats_->proto_stats_[1].keepalive++;
    2675         498 : }
    2676             : 
    2677           0 : uint64_t BgpPeer::get_tx_keepalive() const {
    2678           0 :     return peer_stats_->proto_stats_[1].keepalive;
    2679             : }
    2680             : 
    2681        5303 : void BgpPeer::inc_rx_update() {
    2682        5303 :     peer_stats_->proto_stats_[0].update++;
    2683        5303 : }
    2684             : 
    2685           0 : uint64_t BgpPeer::get_rx_update() const {
    2686           0 :     return peer_stats_->proto_stats_[0].update;
    2687             : }
    2688             : 
    2689        5305 : void BgpPeer::inc_tx_update() {
    2690        5305 :     peer_stats_->proto_stats_[1].update++;
    2691        5305 : }
    2692             : 
    2693           0 : uint64_t BgpPeer::get_tx_update() const {
    2694           0 :     return peer_stats_->proto_stats_[1].update;
    2695             : }
    2696             : 
    2697         377 : void BgpPeer::inc_rx_notification() {
    2698         377 :     peer_stats_->proto_stats_[0].notification++;
    2699         377 : }
    2700             : 
    2701           0 : uint64_t BgpPeer::get_rx_notification() const {
    2702           0 :     return peer_stats_->proto_stats_[0].notification;
    2703             : }
    2704             : 
    2705         485 : void BgpPeer::inc_tx_notification() {
    2706         485 :     peer_stats_->proto_stats_[1].notification++;
    2707         485 : }
    2708             : 
    2709         688 : void BgpPeer::inc_rx_end_of_rib() {
    2710         688 :     peer_stats_->update_stats_[0].end_of_rib++;
    2711         688 : }
    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         690 : void BgpPeer::inc_tx_end_of_rib() {
    2718         690 :     peer_stats_->update_stats_[1].end_of_rib++;
    2719         690 : }
    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        4615 : void BgpPeer::inc_rx_route_reach(uint64_t count) {
    2726        4615 :     peer_stats_->update_stats_[0].reach += count;
    2727        4615 : }
    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        4615 : void BgpPeer::inc_rx_route_unreach(uint64_t count) {
    2738        4615 :     peer_stats_->update_stats_[0].unreach += count;
    2739        4615 : }
    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          32 : void BgpPeer::inc_hold_timer_expired() {
    2770          32 :     peer_stats_->error_stats_.hold_timer++;
    2771          32 : }
    2772             : 
    2773         101 : void BgpPeer::inc_open_error() {
    2774         101 :     peer_stats_->error_stats_.open_error++;
    2775         101 : }
    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         498 : void BgpPeer::increment_flap_count() {
    2822         498 :     flap_count_++;
    2823         498 :     total_flap_count_++;
    2824         498 :     last_flap_ = UTCTimestampUsec();
    2825             : 
    2826         996 :     BgpPeerInfoData peer_info;
    2827         498 :     peer_info.set_name(ToUVEKey());
    2828         498 :     PeerFlapInfo flap_info;
    2829         498 :     flap_info.set_flap_count(flap_count_);
    2830         498 :     flap_info.set_flap_time(last_flap_);
    2831         498 :     peer_info.set_flap_info(flap_info);
    2832         498 :     BGPPeerInfoSend(peer_info);
    2833             : 
    2834         996 :     PeerFlapData peer_flap_data;
    2835         498 :     peer_flap_data.set_name(ToUVEKey());
    2836         498 :     peer_flap_data.set_flap_info(flap_info);
    2837         498 :     assert(!peer_flap_data.get_name().empty());
    2838         498 :     BGP_UVE_SEND2(PeerFlap, peer_flap_data, "ObjectBgpPeer");
    2839         498 : }
    2840             : 
    2841           0 : void BgpPeer::reset_flap_count() {
    2842           0 :     flap_count_ = 0;
    2843           0 :     last_flap_ = 0;
    2844             : 
    2845           0 :     BgpPeerInfoData peer_info;
    2846           0 :     peer_info.set_name(ToUVEKey());
    2847           0 :     PeerFlapInfo flap_info;
    2848           0 :     peer_info.set_flap_info(flap_info);
    2849           0 :     BGPPeerInfoSend(peer_info);
    2850             : 
    2851           0 :     PeerFlapData peer_flap_data;
    2852           0 :     peer_flap_data.set_name(ToUVEKey());
    2853           0 :     peer_flap_data.set_flap_info(flap_info);
    2854           0 :     assert(!peer_flap_data.get_name().empty());
    2855           0 :     BGP_UVE_SEND2(PeerFlap, peer_flap_data, "ObjectBgpPeer");
    2856           0 : }
    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         545 : bool BgpPeer::ProcessSession() const {
    2861         545 :     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 : }

Generated by: LCOV version 1.14