LCOV - code coverage report
Current view: top level - bgp/routing-instance - routing_instance.cc (source / functions) Hit Total Coverage
Test: OpenSDN C/C++ coverage (all TARGET_SET jobs) Lines: 804 1224 65.7 %
Date: 2026-11-16 02:06:09 Functions: 94 129 72.9 %
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/routing-instance/routing_instance.h"
       7             : 
       8             : #include <boost/foreach.hpp>
       9             : #include <boost/assign/list_of.hpp>
      10             : #include <boost/functional/hash.hpp>
      11             : 
      12             : #include <algorithm>
      13             : 
      14             : #include "base/set_util.h"
      15             : #include "base/task_annotations.h"
      16             : #include "base/task_trigger.h"
      17             : #include "bgp/bgp_config.h"
      18             : #include "bgp/bgp_factory.h"
      19             : #include "bgp/bgp_log.h"
      20             : #include "bgp/bgp_mvpn.h"
      21             : #include "bgp/bgp_server.h"
      22             : #include "bgp/mvpn/mvpn_table.h"
      23             : #include "bgp/routing-instance/iroute_aggregator.h"
      24             : #include "bgp/routing-instance/istatic_route_mgr.h"
      25             : #include "bgp/routing-instance/peer_manager.h"
      26             : #include "bgp/routing-instance/routepath_replicator.h"
      27             : #include "bgp/routing-instance/routing_instance_log.h"
      28             : #include "bgp/routing-instance/routing_table_types.h"
      29             : #include "bgp/routing-policy/routing_policy.h"
      30             : #include "bgp/routing-instance/rtarget_group_mgr.h"
      31             : #include "bgp/rtarget/rtarget_route.h"
      32             : 
      33             : using boost::assign::list_of;
      34             : using boost::system::error_code;
      35             : using boost::tie;
      36             : using std::make_pair;
      37             : using std::ostringstream;
      38             : using std::set;
      39             : using std::string;
      40             : using std::vector;
      41             : 
      42             : SandeshTraceBufferPtr RoutingInstanceTraceBuf(
      43             :         SandeshTraceBufferCreate(RTINSTANCE_TRACE_BUF, 1000));
      44             : 
      45             : class RoutingInstanceMgr::DeleteActor : public LifetimeActor {
      46             : public:
      47          20 :     explicit DeleteActor(RoutingInstanceMgr *manager)
      48          20 :         : LifetimeActor(manager->server_->lifetime_manager()),
      49          20 :           manager_(manager) {
      50          20 :     }
      51          20 :     virtual bool MayDelete() const {
      52          20 :         return manager_->MayDelete();
      53             :     }
      54          20 :     virtual void Shutdown() {
      55          20 :         manager_->Shutdown();
      56          20 :     }
      57          20 :     virtual void Destroy() {
      58          20 :         manager_->server_delete_ref_.Reset(NULL);
      59          20 :     }
      60             : 
      61             : private:
      62             :     RoutingInstanceMgr *manager_;
      63             : };
      64             : 
      65          20 : RoutingInstanceMgr::RoutingInstanceMgr(BgpServer *server) :
      66          20 :         server_(server),
      67          40 :         instance_config_lists_(
      68          20 :             TaskScheduler::GetInstance()->HardwareThreadCount()),
      69          20 :         default_rtinstance_(NULL),
      70          20 :         deleted_count_(0),
      71          20 :         asn_listener_id_(server->RegisterASNUpdateCallback(
      72             :             boost::bind(&RoutingInstanceMgr::ASNUpdateCallback, this, _1, _2))),
      73          20 :         identifier_listener_id_(server->RegisterIdentifierUpdateCallback(
      74             :             boost::bind(&RoutingInstanceMgr::IdentifierUpdateCallback,
      75             :                 this, _1))),
      76          20 :         dormant_trace_buf_size_(
      77          20 :                 GetEnvRoutingInstanceDormantTraceBufferCapacity()),
      78          20 :         trace_buf_threshold_(
      79          20 :                 GetEnvRoutingInstanceDormantTraceBufferThreshold()),
      80          20 :         deleter_(new DeleteActor(this)),
      81          60 :         server_delete_ref_(this, server->deleter()) {
      82          20 :     int task_id = TaskScheduler::GetInstance()->GetTaskId("bgp::ConfigHelper");
      83          20 :     int hw_thread_count = TaskScheduler::GetInstance()->HardwareThreadCount();
      84         100 :     for (int idx = 0; idx < hw_thread_count; ++idx) {
      85         160 :         instance_config_triggers_.push_back(new TaskTrigger(boost::bind(
      86             :             &RoutingInstanceMgr::ProcessInstanceConfigList, this, idx),
      87          80 :             task_id, idx));
      88             :     }
      89          40 :     neighbor_config_trigger_.reset(new TaskTrigger(
      90             :         boost::bind(&RoutingInstanceMgr::ProcessNeighborConfigList, this),
      91          40 :         TaskScheduler::GetInstance()->GetTaskId("bgp::Config"), 0));
      92          20 : }
      93             : 
      94          40 : RoutingInstanceMgr::~RoutingInstanceMgr() {
      95          20 :     assert(mvpn_project_managers_.empty());
      96          20 :     assert(virtual_networks_.empty());
      97          20 :     assert(deleted_count_ == 0);
      98          20 :     server_->UnregisterASNUpdateCallback(asn_listener_id_);
      99          20 :     server_->UnregisterIdentifierUpdateCallback(identifier_listener_id_);
     100          20 :     STLDeleteValues(&instance_config_triggers_);
     101          40 : }
     102             : 
     103           0 : size_t RoutingInstanceMgr::GetMvpnProjectManagerCount(
     104             :             const string &network) const {
     105           0 :     std::scoped_lock lock(mutex_);
     106             : 
     107             :     MvpnProjectManagerNetworks::const_iterator iter =
     108           0 :         mvpn_project_managers_.find(network);
     109           0 :     if (iter == mvpn_project_managers_.end())
     110           0 :         return 0;
     111           0 :     return iter->second.size();
     112           0 : }
     113             : 
     114          20 : void RoutingInstanceMgr::ManagedDelete() {
     115          20 :     deleter_->Delete();
     116          20 : }
     117             : 
     118          20 : void RoutingInstanceMgr::Shutdown() {
     119         120 :     for (RoutingInstanceIterator it = begin(); it != end(); ++it) {
     120         100 :         InstanceTargetRemove(it->second);
     121         100 :         InstanceVnIndexRemove(it->second);
     122             :     }
     123          20 : }
     124             : 
     125          20 : bool RoutingInstanceMgr::MayDelete() const {
     126          20 :     if (!neighbor_config_list_.empty())
     127           0 :         return false;
     128         100 :     for (size_t idx = 0; idx < instance_config_lists_.size(); ++idx) {
     129          80 :         if (!instance_config_lists_[idx].empty())
     130           0 :             return false;
     131             :     }
     132          20 :     return true;
     133             : }
     134             : 
     135         261 : LifetimeActor *RoutingInstanceMgr::deleter() {
     136         261 :     return deleter_.get();
     137             : }
     138             : 
     139         161 : bool RoutingInstanceMgr::deleted() {
     140         161 :     return deleter()->IsDeleted();
     141             : }
     142             : 
     143             : //
     144             : // Go through all export targets for the RoutingInstance and add an entry for
     145             : // each one to the InstanceTargetMap.
     146             : //
     147             : // Ignore export targets that are not in the import list.  This is done since
     148             : // export only targets are managed by user and the same export only target can
     149             : // be configured on multiple virtual networks.
     150             : //
     151         141 : void RoutingInstanceMgr::InstanceTargetAdd(RoutingInstance *rti) {
     152         141 :     std::scoped_lock lock(mutex_);
     153         141 :     for (RoutingInstance::RouteTargetList::const_iterator it =
     154         603 :          rti->GetExportList().begin(); it != rti->GetExportList().end(); ++it) {
     155         321 :         if (rti->GetImportList().find(*it) == rti->GetImportList().end())
     156           0 :             continue;
     157         321 :         target_map_.insert(make_pair(*it, rti));
     158             :     }
     159         141 : }
     160             : 
     161             : //
     162             : // Go through all export targets for the RoutingInstance and remove the entry
     163             : // for each one from the InstanceTargetMap.  Note that there may be multiple
     164             : // entries in the InstanceTargetMap for a given export target.  Hence we need
     165             : // to make sure that we only remove the entry that matches the RoutingInstance.
     166             : //
     167             : // Ignore export targets that are not in the import list. They shouldn't be in
     168             : // in the map because of the same check in InstanceTargetAdd.
     169             : //
     170         141 : void RoutingInstanceMgr::InstanceTargetRemove(const RoutingInstance *rti) {
     171         141 :     std::scoped_lock lock(mutex_);
     172         141 :     for (RoutingInstance::RouteTargetList::const_iterator it =
     173         603 :          rti->GetExportList().begin(); it != rti->GetExportList().end(); ++it) {
     174         321 :         if (rti->GetImportList().find(*it) == rti->GetImportList().end())
     175           0 :             continue;
     176         321 :         for (InstanceTargetMap::iterator loc = target_map_.find(*it);
     177         575 :              loc != target_map_.end() && loc->first == *it; ++loc) {
     178         575 :             if (loc->second == rti) {
     179         321 :                 target_map_.erase(loc);
     180         321 :                 break;
     181             :             }
     182             :         }
     183             :     }
     184         141 : }
     185             : 
     186             : //
     187             : // Lookup the RoutingInstance for the given RouteTarget.
     188             : //
     189           0 : const RoutingInstance *RoutingInstanceMgr::GetInstanceByTarget(
     190             :         const RouteTarget &rtarget) const {
     191           0 :     InstanceTargetMap::const_iterator loc = target_map_.find(rtarget);
     192           0 :     if (loc == target_map_.end()) {
     193           0 :         return NULL;
     194             :     }
     195           0 :     return loc->second;
     196             : }
     197             : 
     198             : //
     199             : // Add an entry for the vn index to the VnIndexMap.
     200             : //
     201         141 : void RoutingInstanceMgr::InstanceVnIndexAdd(RoutingInstance *rti) {
     202         141 :     std::scoped_lock lock(mutex_);
     203         141 :     if (rti->virtual_network_index())
     204           0 :         vn_index_map_.insert(make_pair(rti->virtual_network_index(), rti));
     205         141 : }
     206             : 
     207             : //
     208             : // Remove the entry for the vn index from the VnIndexMap.  Note that there may
     209             : // be multiple entries in the VnIndexMap for a given vn index target. Hence we
     210             : // need to make sure that we remove the entry that matches the RoutingInstance.
     211             : //
     212         141 : void RoutingInstanceMgr::InstanceVnIndexRemove(const RoutingInstance *rti) {
     213         141 :     std::scoped_lock lock(mutex_);
     214         141 :     if (!rti->virtual_network_index())
     215         141 :         return;
     216             : 
     217           0 :     int vn_index = rti->virtual_network_index();
     218           0 :     for (VnIndexMap::iterator loc = vn_index_map_.find(vn_index);
     219           0 :          loc != vn_index_map_.end() && loc->first == vn_index; ++loc) {
     220           0 :         if (loc->second == rti) {
     221           0 :             vn_index_map_.erase(loc);
     222           0 :             break;
     223             :         }
     224             :     }
     225         141 : }
     226             : 
     227             : //
     228             : // Lookup the RoutingInstance for the given vn index.
     229             : //
     230           0 : const RoutingInstance *RoutingInstanceMgr::GetInstanceByVnIndex(
     231             :         int vn_index) const {
     232           0 :     VnIndexMap::const_iterator loc = vn_index_map_.find(vn_index);
     233           0 :     if (loc == vn_index_map_.end())
     234           0 :         return NULL;
     235           0 :     return loc->second;
     236             : }
     237             : 
     238             : //
     239             : // Lookup the VN name for the given vn index.
     240             : //
     241           0 : string RoutingInstanceMgr::GetVirtualNetworkByVnIndex(
     242             :         int vn_index) const {
     243           0 :     const RoutingInstance *rti = GetInstanceByVnIndex(vn_index);
     244           0 :     return rti ? rti->GetVirtualNetworkName() : "unresolved";
     245             : }
     246             : 
     247             : //
     248             : // Lookup the vn index for the given RouteTarget.
     249             : //
     250             : // Return 0 if the RouteTarget does not map to a RoutingInstance.
     251             : // Return -1 if the RouteTarget maps to multiple RoutingInstances
     252             : // that belong to different VNs.
     253             : //
     254       46082 : int RoutingInstanceMgr::GetVnIndexByRouteTarget(
     255             :         const RouteTarget &rtarget) const {
     256       46082 :     int vn_index = 0;
     257       46082 :     for (InstanceTargetMap::const_iterator loc = target_map_.find(rtarget);
     258      229895 :          loc != target_map_.end() && loc->first == rtarget; ++loc) {
     259      183868 :         int ri_vn_index = loc->second->virtual_network_index();
     260      183814 :         if (vn_index && ri_vn_index && ri_vn_index != vn_index)
     261           0 :             return -1;
     262      183814 :         vn_index = ri_vn_index;
     263             :     }
     264             : 
     265       46110 :     return vn_index;
     266             : }
     267             : 
     268             : //
     269             : // Derive the vn index from the route targets in the ExtCommunity.
     270             : //
     271             : // If the result is ambiguous i.e. we have a RouteTarget that maps
     272             : // to multiple vn indexes or we have multiple RouteTargets that map
     273             : // to different vn indexes, return 0.
     274             : //
     275       11537 : int RoutingInstanceMgr::GetVnIndexByExtCommunity(
     276             :         const ExtCommunity *ext_community) const {
     277       11537 :     int vn_index = 0;
     278      146356 :     BOOST_FOREACH(const ExtCommunity::ExtCommunityValue &comm,
     279             :                   ext_community->communities()) {
     280       67366 :         if (!ExtCommunity::is_route_target(comm))
     281       21340 :             continue;
     282             : 
     283       46009 :         RouteTarget rtarget(comm);
     284       46084 :         int rtgt_vn_index = GetVnIndexByRouteTarget(rtarget);
     285       46110 :         if (rtgt_vn_index < 0 ||
     286           0 :             (vn_index && rtgt_vn_index && rtgt_vn_index != vn_index)) {
     287           0 :             vn_index = 0;
     288           0 :             break;
     289       46110 :         } else if (rtgt_vn_index) {
     290           0 :             vn_index = rtgt_vn_index;
     291             :         }
     292             :     }
     293             : 
     294       11548 :     return vn_index;
     295             : }
     296             : 
     297             : int
     298         100 : RoutingInstanceMgr::RegisterInstanceOpCallback(RoutingInstanceCb callback) {
     299         100 :     std::scoped_lock lock(mutex_);
     300         100 :     size_t i = bmap_.find_first();
     301         100 :     if (i == bmap_.npos) {
     302         100 :         i = callbacks_.size();
     303         100 :         callbacks_.push_back(callback);
     304             :     } else {
     305           0 :         bmap_.reset(i);
     306           0 :         if (bmap_.none()) {
     307           0 :             bmap_.clear();
     308             :         }
     309           0 :         callbacks_[i] = callback;
     310             :     }
     311         100 :     return i;
     312         100 : }
     313             : 
     314         100 : void RoutingInstanceMgr::UnregisterInstanceOpCallback(int listener) {
     315         100 :     std::scoped_lock lock(mutex_);
     316         100 :     callbacks_[listener] = NULL;
     317         100 :     if ((size_t) listener == callbacks_.size() - 1) {
     318         140 :         while (!callbacks_.empty() && callbacks_.back() == NULL) {
     319         100 :             callbacks_.pop_back();
     320             :         }
     321          40 :         if (bmap_.size() > callbacks_.size()) {
     322          20 :             bmap_.resize(callbacks_.size());
     323             :         }
     324             :     } else {
     325          60 :         if ((size_t) listener >= bmap_.size()) {
     326          60 :             bmap_.resize(listener + 1);
     327             :         }
     328          60 :         bmap_.set(listener);
     329             :     }
     330         100 : }
     331             : 
     332         241 : void RoutingInstanceMgr::NotifyInstanceOp(string name, Operation op) {
     333         241 :     std::scoped_lock lock(mutex_);
     334         241 :     for (InstanceOpListenersList::iterator iter = callbacks_.begin();
     335         926 :          iter != callbacks_.end(); ++iter) {
     336         685 :         if (*iter != NULL) {
     337         685 :             RoutingInstanceCb cb = *iter;
     338         685 :             (cb)(name, op);
     339         685 :         }
     340             :     }
     341         241 : }
     342             : 
     343          61 : bool RoutingInstanceMgr::ProcessInstanceConfigList(int idx) {
     344          61 :     if (deleted()) {
     345           0 :         deleter()->RetryDelete();
     346             :     } else {
     347         223 :         BOOST_FOREACH(const string &name, instance_config_lists_[idx]) {
     348             :             const BgpInstanceConfig *config =
     349          81 :                 server()->config_manager()->FindInstance(name);
     350          80 :             if (!config)
     351           0 :                 continue;
     352          80 :             LocateRoutingInstance(config);
     353             :         }
     354             :     }
     355             : 
     356          61 :     instance_config_lists_[idx].clear();
     357          61 :     return true;
     358             : }
     359             : 
     360        3835 : RoutingInstance *RoutingInstanceMgr::GetDefaultRoutingInstance() {
     361        3835 :     return default_rtinstance_;
     362             : }
     363             : 
     364           0 : const RoutingInstance *RoutingInstanceMgr::GetDefaultRoutingInstance() const {
     365           0 :     return default_rtinstance_;
     366             : }
     367             : 
     368        1920 : RoutingInstance *RoutingInstanceMgr::GetRoutingInstance(const string &name) {
     369        1920 :     RoutingInstanceList::iterator iter = instances_.find(name);
     370        1920 :     if (iter != instances_.end())
     371        1920 :         return iter->second;
     372           0 :     return NULL;
     373             : }
     374             : 
     375           0 : const RoutingInstance *RoutingInstanceMgr::GetRoutingInstance(
     376             :     const string &name) const {
     377           0 :     RoutingInstanceList::const_iterator iter = instances_.find(name);
     378           0 :     if (iter != instances_.end())
     379           0 :         return iter->second;
     380           0 :     return NULL;
     381             : }
     382             : 
     383         140 : RoutingInstance *RoutingInstanceMgr::GetRoutingInstanceLocked(
     384             :     const string &name) {
     385         140 :     std::scoped_lock lock(mutex_);
     386         141 :     RoutingInstanceList::iterator iter = instances_.find(name);
     387         141 :     if (iter != instances_.end())
     388          41 :         return iter->second;
     389         100 :     return NULL;
     390         141 : }
     391             : 
     392         100 : void RoutingInstanceMgr::InsertRoutingInstance(RoutingInstance *rtinstance) {
     393         100 :     std::scoped_lock lock(mutex_);
     394         100 :     instances_.insert(make_pair(rtinstance->config()->name(),
     395             :                 rtinstance));
     396         100 : }
     397             : 
     398         140 : void RoutingInstanceMgr::LocateRoutingInstance(
     399             :     const BgpInstanceConfig *config) {
     400         140 :     RoutingInstance *rtinstance = GetRoutingInstanceLocked(config->name());
     401         141 :     if (rtinstance) {
     402          41 :         if (rtinstance->deleted()) {
     403           0 :             RTINSTANCE_LOG_WARNING_MESSAGE(server_,
     404             :                 RTINSTANCE_LOG_FLAG_ALL, rtinstance->GetVirtualNetworkName(),
     405             :                 config->name(),
     406             :                 "Instance recreated before pending deletion is complete");
     407             :         } else {
     408          41 :             UpdateRoutingInstance(rtinstance, config);
     409             :         }
     410             :     } else {
     411         100 :         rtinstance = CreateRoutingInstance(config);
     412             :     }
     413         141 : }
     414             : 
     415         300 : void RoutingInstanceMgr::LocateRoutingInstance(const string &name) {
     416             :     static boost::hash<string> string_hash;
     417             : 
     418         300 :     if (name == BgpConfigManager::kMasterInstance) {
     419             :         const BgpInstanceConfig *config =
     420          60 :             server()->config_manager()->FindInstance(name);
     421          60 :         assert(config);
     422          60 :         LocateRoutingInstance(config);
     423             :     } else {
     424         240 :         size_t idx = string_hash(name) % instance_config_lists_.size();
     425         240 :         instance_config_lists_[idx].insert(name);
     426         240 :         instance_config_triggers_[idx]->Set();
     427             :     }
     428         300 : }
     429             : 
     430             : // Update VirtualNetwork to RoutingInstance name mapping.
     431         100 : bool RoutingInstanceMgr::CreateVirtualNetworkMapping(
     432             :         const string &virtual_network, const string &instance_name) {
     433         100 :     std::scoped_lock lock(mutex_);
     434             : 
     435         100 :     VirtualNetworksMap::iterator iter;
     436             :     bool inserted;
     437         200 :     tie(iter, inserted) = virtual_networks_.insert(make_pair(virtual_network,
     438         300 :                                                              set<string>()));
     439         100 :     assert(iter->second.insert(instance_name).second);
     440         100 :     return true;
     441         100 : }
     442             : 
     443         100 : bool RoutingInstanceMgr::DeleteVirtualNetworkMapping(
     444             :         const string &virtual_network, const string &instance_name) {
     445         100 :     std::scoped_lock lock(mutex_);
     446             : 
     447         100 :     VirtualNetworksMap::iterator iter = virtual_networks_.find(virtual_network);
     448         100 :     assert(iter != virtual_networks_.end());
     449             : 
     450             :     // Delete this instance from the set of virtual-network to instances map.
     451         100 :     assert(iter->second.erase(instance_name) == 1);
     452             : 
     453         200 :     RoutingInstanceStatsData instance_info;
     454         100 :     bool mapping_deleted = iter->second.empty();
     455             : 
     456             :     // Delete the mapping if the member set is empty.
     457         100 :     if (mapping_deleted) {
     458         100 :         virtual_networks_.erase(iter);
     459             : 
     460             :         // Delete the virtual-network specific UVE.
     461         100 :         instance_info.set_deleted(true);
     462             :     } else {
     463             : 
     464             :         // Delete this instance's uve, by deleting all table stats.
     465           0 :         map<string, RoutingTableStats> stats_map;
     466           0 :         stats_map.insert(make_pair(instance_name, RoutingTableStats()));
     467           0 :         stats_map[instance_name].set_deleted(true);
     468             : 
     469             :         // Delete all uve stats across all address families.
     470           0 :         for (Address::Family i = Address::UNSPEC; i < Address::NUM_FAMILIES;
     471           0 :                 i = static_cast<Address::Family>(i + 1)) {
     472           0 :             SetTableStatsUve(i, stats_map, &instance_info);
     473             :         }
     474           0 :     }
     475             : 
     476             :     // Send delete uve.
     477         100 :     instance_info.set_name(virtual_network);
     478         100 :     assert(!instance_info.get_name().empty());
     479         100 :     BGP_UVE_SEND(RoutingInstanceStats, instance_info);
     480             : 
     481         100 :     return mapping_deleted;
     482         100 : }
     483             : 
     484           0 : void RoutingInstanceMgr::SetTableStatsUve(Address::Family family,
     485             :                              const map<string, RoutingTableStats> &stats_map,
     486             :                              RoutingInstanceStatsData *instance_info) const {
     487             :     // By switching over all families, we get compiler to tell us in future,
     488             :     // when ever familiy enum list gets modified.
     489           0 :     switch (family) {
     490           0 :     case Address::UNSPEC:
     491           0 :         break;
     492           0 :     case Address::INET:
     493             :     case Address::INETMPLS:
     494           0 :         instance_info->set_raw_ipv4_stats(stats_map);
     495           0 :         break;
     496           0 :     case Address::INET6:
     497           0 :         instance_info->set_raw_ipv6_stats(stats_map);
     498           0 :         break;
     499           0 :     case Address::INETVPN:
     500           0 :         instance_info->set_raw_inetvpn_stats(stats_map);
     501           0 :         break;
     502           0 :     case Address::INET6VPN:
     503           0 :         instance_info->set_raw_inet6vpn_stats(stats_map);
     504           0 :         break;
     505           0 :     case Address::RTARGET:
     506           0 :         instance_info->set_raw_rtarget_stats(stats_map);
     507           0 :         break;
     508           0 :     case Address::EVPN:
     509           0 :         instance_info->set_raw_evpn_stats(stats_map);
     510           0 :         break;
     511           0 :     case Address::ERMVPN:
     512           0 :         instance_info->set_raw_ermvpn_stats(stats_map);
     513           0 :         break;
     514           0 :     case Address::MVPN:
     515           0 :         instance_info->set_raw_mvpn_stats(stats_map);
     516           0 :         break;
     517           0 :     case Address::NUM_FAMILIES:
     518           0 :         break;
     519             :     }
     520           0 : }
     521             : 
     522           0 : uint32_t RoutingInstanceMgr::SendTableStatsUve() {
     523           0 :     uint32_t out_q_depth = 0;
     524             : 
     525           0 :     for (RoutingInstanceIterator rit = begin(); rit != end(); ++rit) {
     526           0 :         RoutingInstanceStatsData instance_info;
     527           0 :         map<string, RoutingTableStats> stats_map;
     528             : 
     529           0 :         stats_map.insert(make_pair(rit->second->name(), RoutingTableStats()));
     530             :         RoutingInstance::RouteTableList const rt_list =
     531           0 :                                          rit->second->GetTables();
     532             : 
     533             :         // Prepare and send Statistics UVE for each routing-instance.
     534           0 :         for (RoutingInstance::RouteTableList::const_iterator it =
     535           0 :              rt_list.begin(); it != rt_list.end(); ++it) {
     536           0 :             BgpTable *table = it->second;
     537             : 
     538             :             size_t markers;
     539           0 :             out_q_depth += table->GetPendingRiboutsCount(&markers);
     540             : 
     541           0 :             stats_map[rit->second->name()].set_prefixes(table->Size());
     542           0 :             stats_map[rit->second->name()].set_primary_paths(
     543             :                 table->GetPrimaryPathCount());
     544           0 :             stats_map[rit->second->name()].set_secondary_paths(
     545             :                 table->GetSecondaryPathCount());
     546           0 :             stats_map[rit->second->name()].set_infeasible_paths(
     547             :                 table->GetInfeasiblePathCount());
     548             : 
     549           0 :             uint64_t total_paths = table->GetPrimaryPathCount() +
     550           0 :                                    table->GetSecondaryPathCount() +
     551           0 :                                    table->GetInfeasiblePathCount();
     552           0 :             stats_map[rit->second->name()].set_total_paths(total_paths);
     553           0 :             SetTableStatsUve(table->family(), stats_map, &instance_info);
     554             :         }
     555             : 
     556             :         // Set the primary key and trigger uve send.
     557           0 :         instance_info.set_name(rit->second->GetVirtualNetworkName());
     558           0 :         assert(!instance_info.get_name().empty());
     559           0 :         BGP_UVE_SEND(RoutingInstanceStats, instance_info);
     560           0 :     }
     561             : 
     562           0 :     return out_q_depth;
     563             : }
     564             : 
     565         100 : RoutingInstance *RoutingInstanceMgr::CreateRoutingInstance(
     566             :     const BgpInstanceConfig *config) {
     567         100 :     RoutingInstance *rtinstance = BgpStaticObjectFactory::Create<RoutingInstance>(
     568         100 :         config->name(), server_, this, config);
     569         100 :     uint32_t ri_index = config->index();
     570         100 :     if (config->name() == BgpConfigManager::kMasterInstance) {
     571          20 :         default_rtinstance_ = rtinstance;
     572          20 :         ri_index = 0;
     573             :     }
     574             : 
     575         100 :     rtinstance->ProcessConfig();
     576         100 :     InsertRoutingInstance(rtinstance);
     577         100 :     rtinstance->set_index(ri_index);
     578             : 
     579         100 :     InstanceTargetAdd(rtinstance);
     580         100 :     InstanceVnIndexAdd(rtinstance);
     581         100 :     rtinstance->InitAllRTargetRoutes(server_->local_autonomous_system());
     582             : 
     583             :     // Notify clients about routing instance create
     584         100 :     NotifyInstanceOp(config->name(), INSTANCE_ADD);
     585             : 
     586         100 :     vector<string> import_rt(config->import_list().begin(),
     587         200 :                                   config->import_list().end());
     588         100 :     vector<string> export_rt(config->export_list().begin(),
     589         200 :                                   config->export_list().end());
     590         100 :     RTINSTANCE_LOG(Create, rtinstance,
     591             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL,
     592             :         import_rt, export_rt, rtinstance->virtual_network_index());
     593             : 
     594             :     // Schedule creation of neighbors for this instance.
     595         100 :     CreateRoutingInstanceNeighbors(config);
     596             : 
     597             :     //  Update instance to virtual-network mapping structures.
     598         100 :     CreateVirtualNetworkMapping(rtinstance->GetVirtualNetworkName(),
     599             :                                 rtinstance->name());
     600             : 
     601             :     // Create MvpnManager for all children mvpn networks.
     602             :     MvpnTable *mvpn_table =
     603         100 :         dynamic_cast<MvpnTable *>(rtinstance->GetTable(Address::MVPN));
     604         100 :     mvpn_table->CreateMvpnManagers();
     605         100 :     return rtinstance;
     606         100 : }
     607             : 
     608          41 : void RoutingInstanceMgr::UpdateRoutingInstance(RoutingInstance *rtinstance,
     609             :     const BgpInstanceConfig *config) {
     610          41 :     bool old_always_subscribe = rtinstance->always_subscribe();
     611             : 
     612             :     // Note that InstanceTarget[Remove|Add] depend on the RouteTargetList in
     613             :     // the RoutingInstance.
     614          41 :     InstanceTargetRemove(rtinstance);
     615          41 :     InstanceVnIndexRemove(rtinstance);
     616          41 :     rtinstance->UpdateConfig(config);
     617          41 :     InstanceTargetAdd(rtinstance);
     618          41 :     InstanceVnIndexAdd(rtinstance);
     619             : 
     620          41 :     if (old_always_subscribe != rtinstance->always_subscribe()) {
     621           0 :         rtinstance->FlushAllRTargetRoutes(server_->local_autonomous_system());
     622           0 :         rtinstance->InitAllRTargetRoutes(server_->local_autonomous_system());
     623             :     }
     624             : 
     625             :     // Notify clients about routing instance create
     626          41 :     NotifyInstanceOp(config->name(), INSTANCE_UPDATE);
     627             : 
     628          41 :     vector<string> import_rt(config->import_list().begin(),
     629          82 :                                   config->import_list().end());
     630          41 :     vector<string> export_rt(config->export_list().begin(),
     631          82 :                                   config->export_list().end());
     632          41 :     RTINSTANCE_LOG(Update, rtinstance,
     633             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL, import_rt, export_rt,
     634             :         rtinstance->virtual_network_index());
     635          41 : }
     636             : 
     637             : //
     638             : // Concurrency: BGP Config task
     639             : //
     640             : // Trigger deletion of a particular routing-instance
     641             : //
     642             : // This involves several asynchronous steps such as deleting all tables in
     643             : // routing-instance (flush all notifications, registrations and user data).
     644             : //
     645           0 : void RoutingInstanceMgr::DeleteRoutingInstance(const string &name) {
     646           0 :     CHECK_CONCURRENCY("bgp::Config");
     647             : 
     648           0 :     RoutingInstance *rtinstance = GetRoutingInstance(name);
     649             : 
     650             :     // Ignore if instance is not found as it might already have been deleted.
     651           0 :     if (rtinstance && rtinstance->deleted()) {
     652           0 :         RTINSTANCE_LOG_WARNING_MESSAGE(server_, RTINSTANCE_LOG_FLAG_ALL,
     653             :             rtinstance->GetVirtualNetworkName(), name,
     654             :             "Duplicate instance delete while pending deletion");
     655           0 :         return;
     656           0 :     } else if (!rtinstance) {
     657           0 :         RTINSTANCE_LOG_WARNING_MESSAGE(server_, RTINSTANCE_LOG_FLAG_ALL,
     658             :             name, name, "Instance not found during delete");
     659           0 :         return;
     660             :     }
     661             : 
     662           0 :     InstanceVnIndexRemove(rtinstance);
     663           0 :     InstanceTargetRemove(rtinstance);
     664           0 :     rtinstance->ClearConfig();
     665             : 
     666           0 :     RTINSTANCE_LOG(Delete, rtinstance,
     667             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL);
     668             : 
     669           0 :     rtinstance->ProcessServiceChainConfig();
     670           0 :     rtinstance->FlushStaticRouteConfig();
     671           0 :     rtinstance->FlushRouteAggregationConfig();
     672             : 
     673           0 :     NotifyInstanceOp(name, INSTANCE_DELETE);
     674           0 :     rtinstance->ManagedDelete();
     675             : }
     676             : 
     677             : //
     678             : // Concurrency: Called from BGP config task manager
     679             : //
     680             : // Destroy a routing instance from the data structures
     681             : //
     682         100 : void RoutingInstanceMgr::DestroyRoutingInstance(RoutingInstance *rtinstance) {
     683         100 :     CHECK_CONCURRENCY("bgp::Config");
     684             : 
     685         100 :     RTINSTANCE_LOG(Destroy, rtinstance,
     686             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL);
     687             : 
     688         100 :     DeleteVirtualNetworkMapping(rtinstance->GetVirtualNetworkName(),
     689             :                                 rtinstance->name());
     690             : 
     691             :     // instance should also be deleted here
     692         100 :     const string name = rtinstance->name();
     693         100 :     RoutingInstanceList::iterator loc = instances_.find(rtinstance->name());
     694         100 :     assert(loc != instances_.end());
     695         100 :     instances_.erase(loc);
     696         100 :     int index = rtinstance->index();
     697         100 :     delete rtinstance;
     698             :     // disable the TraceBuf for the deleted RoutingInstance
     699         100 :     DisableTraceBuffer(name);
     700             :     // index was allocated in Config Manager so needs to be freed
     701         100 :     if (index >= 0)
     702         100 :         server()->config_manager()->ResetRoutingInstanceIndexBit(index);
     703             : 
     704         100 :     if (deleted())
     705         100 :         return;
     706             : 
     707           0 :     if (rtinstance == default_rtinstance_) {
     708           0 :         default_rtinstance_ = NULL;
     709           0 :         return;
     710             :     }
     711             : 
     712             :     const BgpInstanceConfig *config
     713           0 :         = server()->config_manager()->FindInstance(name);
     714           0 :     if (config) {
     715           0 :         CreateRoutingInstance(config);
     716           0 :         return;
     717             :     }
     718         100 : }
     719             : 
     720        1625 : SandeshTraceBufferPtr RoutingInstanceMgr::LocateTraceBuffer(
     721             :         const std::string &name) {
     722        1625 :     SandeshTraceBufferPtr trace_buf;
     723             : 
     724        1625 :     trace_buf = GetActiveTraceBuffer(name);
     725        1624 :     if (trace_buf == NULL) {
     726         100 :         trace_buf = GetTraceBuffer(name);
     727             :     }
     728             : 
     729        1625 :     return trace_buf;
     730           0 : }
     731             : 
     732         100 : SandeshTraceBufferPtr RoutingInstanceMgr::GetTraceBuffer(
     733             :         const std::string &name) {
     734         100 :     tbb::spin_rw_mutex::scoped_lock write_lock(rw_mutex_, true);
     735         100 :     SandeshTraceBufferPtr trace_buf;
     736         100 :     RoutingInstanceTraceBufferMap::iterator iter;
     737             : 
     738         100 :     iter = trace_buffer_active_.find(name);
     739         100 :     if (iter != trace_buffer_active_.end()) {
     740           0 :         return iter->second;
     741             :     }
     742             : 
     743         100 :     iter = trace_buffer_dormant_.find(name);
     744         100 :     if (iter != trace_buffer_dormant_.end()) {
     745             :         // tracebuf was created for this RoutingInstance in its prior
     746             :         // incarnation
     747           0 :         trace_buf = iter->second;
     748           0 :         trace_buffer_dormant_.erase(iter);
     749           0 :         trace_buffer_dormant_list_.remove(name);
     750           0 :         trace_buffer_active_.insert(make_pair(name, trace_buf));
     751           0 :         return trace_buf;
     752             :     }
     753             : 
     754             :     // create new sandesh Buffer
     755         200 :     trace_buf = SandeshTraceBufferCreate(
     756         300 :                                   name + RTINSTANCE_TRACE_BUF, 1000);
     757         100 :     trace_buffer_active_.insert(make_pair(name, trace_buf));
     758             : 
     759         100 :     return trace_buf;
     760         100 : }
     761             : 
     762         100 : void RoutingInstanceMgr::DisableTraceBuffer(const std::string &name) {
     763         100 :     tbb::spin_rw_mutex::scoped_lock write_lock(rw_mutex_, true);
     764         100 :     SandeshTraceBufferPtr trace_buf;
     765         100 :     SandeshTraceBufferPtr trace_buf_delete;
     766         100 :     RoutingInstanceTraceBufferMap::iterator iter;
     767         100 :     std::pair<RoutingInstanceTraceBufferMap::iterator, bool> ret;
     768         100 :     std::string ri_name;
     769             : 
     770             :     // Moving the trace buff from Active map to Dormant map
     771         100 :     iter = trace_buffer_active_.find(name);
     772         100 :     if (iter != trace_buffer_active_.end()) {
     773         100 :         trace_buf = iter->second;
     774         100 :         trace_buffer_active_.erase(iter);
     775         100 :         if (dormant_trace_buf_size_) {
     776             :             // Move to Dormant map.
     777           0 :             if (trace_buffer_dormant_.size() >= dormant_trace_buf_size_) {
     778             :                 // Make room in the Dormant map, so creating by:
     779             :                 // 1. Delete oldest entries in dormant map
     780             :                 // 2. Insert the new entry.
     781           0 :                 size_t del_count = std::min(trace_buffer_dormant_list_.size(),
     782           0 :                                                trace_buf_threshold_);
     783           0 :                 if (!del_count) {
     784             :                     // retain the latest deleted RI's TraceBuf
     785           0 :                     del_count = 1;
     786             :                 }
     787           0 :                 for (size_t i = 0; i < del_count; i++) {
     788           0 :                     iter = trace_buffer_dormant_.find(
     789           0 :                             trace_buffer_dormant_list_.front());
     790           0 :                     assert(iter != trace_buffer_dormant_.end());
     791           0 :                     trace_buf_delete = iter->second;
     792           0 :                     trace_buffer_dormant_.erase(iter);
     793           0 :                     trace_buffer_dormant_list_.pop_front();
     794           0 :                     trace_buf_delete.reset();
     795             :                 }
     796             :             }
     797           0 :             ret = trace_buffer_dormant_.insert(make_pair(name, trace_buf));
     798           0 :             assert(ret.second == true);
     799           0 :             trace_buffer_dormant_list_.push_back(name);
     800             :         }
     801             :     }
     802             : 
     803         200 :     return;
     804         100 : }
     805             : 
     806             : SandeshTraceBufferPtr
     807        1625 : RoutingInstanceMgr::GetActiveTraceBuffer(const std::string &name) const {
     808        1625 :     tbb::spin_rw_mutex::scoped_lock read_lock(rw_mutex_, false);
     809             :     RoutingInstanceTraceBufferMap::const_iterator iter =
     810        1625 :                                          trace_buffer_active_.find(name);
     811             : 
     812        1623 :     if (iter != trace_buffer_active_.end()) {
     813        1525 :         return iter->second;
     814             :     } else {
     815          99 :         return SandeshTraceBufferPtr();
     816             :     }
     817        1624 : }
     818             : 
     819             : SandeshTraceBufferPtr
     820           0 : RoutingInstanceMgr::GetDormantTraceBuffer(const std::string &name) const {
     821           0 :     tbb::spin_rw_mutex::scoped_lock read_lock(rw_mutex_, false);
     822             :     RoutingInstanceTraceBufferMap::const_iterator iter =
     823           0 :                                          trace_buffer_dormant_.find(name);
     824             : 
     825           0 :     if (iter != trace_buffer_dormant_.end()) {
     826           0 :         return iter->second;
     827             :     } else {
     828           0 :         return SandeshTraceBufferPtr();
     829             :     }
     830           0 : }
     831             : 
     832           0 : bool RoutingInstanceMgr::HasRoutingInstanceActiveTraceBuf(const std::string
     833             :                                                           &name) const {
     834           0 :     tbb::spin_rw_mutex::scoped_lock read_lock(rw_mutex_, false);
     835             :     RoutingInstanceTraceBufferMap::const_iterator iter =
     836           0 :                                           trace_buffer_active_.find(name);
     837             : 
     838           0 :     return (iter != trace_buffer_active_.end());
     839           0 : }
     840             : 
     841           0 : bool RoutingInstanceMgr::HasRoutingInstanceDormantTraceBuf(const std::string
     842             :                                                            &name) const {
     843           0 :     tbb::spin_rw_mutex::scoped_lock read_lock(rw_mutex_, false);
     844             :     RoutingInstanceTraceBufferMap::const_iterator iter =
     845           0 :                                           trace_buffer_dormant_.find(name);
     846           0 :     return (iter != trace_buffer_dormant_.end());
     847           0 : }
     848             : 
     849             : size_t
     850          20 : RoutingInstanceMgr::GetEnvRoutingInstanceDormantTraceBufferCapacity() const {
     851          20 :     char *buffer_capacity_str = getenv(
     852             :             "CONTRAIL_ROUTING_INSTANCE_DORMANT_TRACE_BUFFER_SIZE");
     853             :     // return Trace buf capacity 0, if not set in env variable.
     854          20 :     if (buffer_capacity_str) {
     855           0 :         size_t env_buffer_capacity = strtoul(buffer_capacity_str, NULL, 0);
     856           0 :         return env_buffer_capacity;
     857             :     }
     858          20 :     return 0;
     859             : }
     860             : 
     861             : size_t
     862          20 : RoutingInstanceMgr::GetEnvRoutingInstanceDormantTraceBufferThreshold() const {
     863          20 :     char *buffer_threshold_str = getenv(
     864             :             "CONTRAIL_ROUTING_INSTANCE_DORMANT_TRACE_BUFFER_THRESHOLD");
     865          20 :     if (buffer_threshold_str) {
     866           0 :         size_t env_buffer_threshold = strtoul(buffer_threshold_str, NULL, 0);
     867           0 :         return env_buffer_threshold;
     868             :     }
     869          20 :     return ROUTING_INSTANCE_DORMANT_TRACE_BUFFER_THRESHOLD_1K;
     870             : }
     871             : 
     872           0 : size_t RoutingInstanceMgr::GetRoutingInstanceActiveTraceBufSize() const {
     873           0 :     tbb::spin_rw_mutex::scoped_lock read_lock(rw_mutex_, false);
     874           0 :     return trace_buffer_active_.size();
     875           0 : }
     876             : 
     877           0 : size_t RoutingInstanceMgr::GetRoutingInstanceDormantTraceBufSize() const {
     878           0 :     tbb::spin_rw_mutex::scoped_lock read_lock(rw_mutex_, false);
     879           0 :     return trace_buffer_dormant_.size();
     880           0 : }
     881             : 
     882         100 : void RoutingInstanceMgr::CreateRoutingInstanceNeighbors(
     883             :     const BgpInstanceConfig *config) {
     884         100 :     if (config->neighbor_list().empty())
     885         100 :         return;
     886           0 :     std::scoped_lock lock(mutex_);
     887           0 :     neighbor_config_list_.insert(config->name());
     888           0 :     neighbor_config_trigger_->Set();
     889           0 : }
     890             : 
     891           0 : bool RoutingInstanceMgr::ProcessNeighborConfigList() {
     892           0 :     if (deleted()) {
     893           0 :         deleter()->RetryDelete();
     894             :     } else {
     895           0 :         BOOST_FOREACH(const string &name, neighbor_config_list_) {
     896           0 :             RoutingInstance *rtinstance = GetRoutingInstance(name);
     897           0 :             if (!rtinstance || rtinstance->deleted())
     898           0 :                 continue;
     899           0 :             rtinstance->CreateNeighbors();
     900             :         }
     901             :     }
     902             : 
     903           0 :     neighbor_config_list_.clear();
     904           0 :     return true;
     905             : }
     906             : 
     907          20 : void RoutingInstanceMgr::ASNUpdateCallback(as_t old_asn, as_t old_local_asn) {
     908          20 :     if (server_->local_autonomous_system() == old_local_asn)
     909           0 :         return;
     910          40 :     for (RoutingInstanceIterator it = begin(); it != end(); ++it) {
     911          20 :         it->second->FlushAllRTargetRoutes(old_local_asn);
     912          20 :         it->second->InitAllRTargetRoutes(server_->local_autonomous_system());
     913             :     }
     914          20 :     RoutingInstance *master = GetDefaultRoutingInstance();
     915          20 :     const Ip4Address old_identifier(server()->bgp_identifier());
     916          20 :     master->DeleteMvpnRTargetRoute(old_local_asn, old_identifier);
     917          20 :     master->AddMvpnRTargetRoute(server_->local_autonomous_system());
     918             : }
     919             : 
     920          20 : void RoutingInstanceMgr::IdentifierUpdateCallback(Ip4Address old_identifier) {
     921          40 :     for (RoutingInstanceIterator it = begin(); it != end(); ++it) {
     922          20 :         it->second->ProcessIdentifierUpdate(server_->local_autonomous_system());
     923             :     }
     924          20 :     RoutingInstance *master = GetDefaultRoutingInstance();
     925          20 :     master->DeleteMvpnRTargetRoute(server_->local_autonomous_system(),
     926             :             old_identifier);
     927          20 :     master->AddMvpnRTargetRoute(server_->local_autonomous_system());
     928          20 : }
     929             : 
     930             : //
     931             : // Disable processing of all instance config lists.
     932             : // For testing only.
     933             : //
     934           0 : void RoutingInstanceMgr::DisableInstanceConfigListProcessing() {
     935           0 :     for (size_t idx = 0; idx < instance_config_triggers_.size(); ++idx) {
     936           0 :         instance_config_triggers_[idx]->set_disable();
     937             :     }
     938           0 : }
     939             : 
     940             : //
     941             : // Enable processing of all instance config lists.
     942             : // For testing only.
     943             : //
     944           0 : void RoutingInstanceMgr::EnableInstanceConfigListProcessing() {
     945           0 :     for (size_t idx = 0; idx < instance_config_triggers_.size(); ++idx) {
     946           0 :         instance_config_triggers_[idx]->set_enable();
     947             :     }
     948           0 : }
     949             : 
     950             : //
     951             : // Disable processing of neighbor config list.
     952             : // For testing only.
     953             : //
     954           0 : void RoutingInstanceMgr::DisableNeighborConfigListProcessing() {
     955           0 :     neighbor_config_trigger_->set_disable();
     956           0 : }
     957             : 
     958             : //
     959             : // Enable processing of neighbor config list.
     960             : // For testing only.
     961             : //
     962           0 : void RoutingInstanceMgr::EnableNeighborConfigListProcessing() {
     963           0 :     neighbor_config_trigger_->set_enable();
     964           0 : }
     965             : 
     966             : class RoutingInstance::DeleteActor : public LifetimeActor {
     967             : public:
     968         100 :     DeleteActor(BgpServer *server, RoutingInstance *parent)
     969         100 :             : LifetimeActor(server ? server->lifetime_manager() : NULL),
     970         200 :                             parent_(parent) {
     971         100 :     }
     972         100 :     virtual bool MayDelete() const {
     973         100 :         return parent_->MayDelete();
     974             :     }
     975         100 :     virtual void Shutdown() {
     976         100 :         parent_->mgr_->increment_deleted_count();
     977         100 :         parent_->mgr_->NotifyInstanceOp(parent_->name(),
     978             :                                         RoutingInstanceMgr::INSTANCE_DELETE);
     979         100 :         parent_->Shutdown();
     980         100 :     }
     981         100 :     virtual void Destroy() {
     982         100 :         parent_->mgr_->decrement_deleted_count();
     983         100 :         parent_->mgr_->DestroyRoutingInstance(parent_);
     984         100 :     }
     985             : 
     986             : private:
     987             :     RoutingInstance *parent_;
     988             : };
     989             : 
     990         100 : RoutingInstance::RoutingInstance(string name, BgpServer *server,
     991             :                                  RoutingInstanceMgr *mgr,
     992         100 :                                  const BgpInstanceConfig *config)
     993         300 :     : name_(name), index_(-1), server_(server), mgr_(mgr), config_(config),
     994         200 :       is_master_(false), always_subscribe_(false), virtual_network_index_(0),
     995         100 :       virtual_network_allow_transit_(false),
     996         100 :       virtual_network_pbb_evpn_enable_(false),
     997         100 :       vxlan_id_(0),
     998         100 :       deleter_(new DeleteActor(server, this)),
     999         100 :       manager_delete_ref_(this, NULL),
    1000         200 :       mvpn_project_manager_network_(BgpConfigManager::kFabricInstance) {
    1001          99 :     if (mgr) {
    1002          99 :         std::scoped_lock lock(mgr->mutex());
    1003         100 :         manager_delete_ref_.Reset(mgr->deleter());
    1004         100 :     }
    1005         100 : }
    1006             : 
    1007         200 : RoutingInstance::~RoutingInstance() {
    1008         200 : }
    1009             : 
    1010           0 : void RoutingInstance::CreateNeighbors() {
    1011           0 :     CHECK_CONCURRENCY("bgp::Config");
    1012             : 
    1013           0 :     if (config_->neighbor_list().empty())
    1014           0 :         return;
    1015           0 :     PeerManager *peer_manager = LocatePeerManager();
    1016           0 :     BOOST_FOREACH(const string &name, config_->neighbor_list()) {
    1017           0 :         if (peer_manager->PeerLookup(name))
    1018           0 :             continue;
    1019           0 :         peer_manager->PeerResurrect(name);
    1020             :     }
    1021             : }
    1022             : 
    1023         100 : void RoutingInstance::ProcessRoutingPolicyConfig() {
    1024         100 :     RoutingPolicyMgr *policy_mgr = server()->routing_policy_mgr();
    1025         100 :     BOOST_FOREACH(RoutingPolicyAttachInfo info,
    1026             :                   config_->routing_policy_list()) {
    1027             :         RoutingPolicy *policy =
    1028           0 :             policy_mgr->GetRoutingPolicy(info.routing_policy_);
    1029           0 :         if (policy) {
    1030           0 :             routing_policies_.push_back(make_pair(policy,
    1031           0 :                                                   policy->generation()));
    1032             :         }
    1033           0 :     }
    1034         100 : }
    1035             : 
    1036        1625 : SandeshTraceBufferPtr RoutingInstance::trace_buffer() const {
    1037        1625 :     return mgr_->LocateTraceBuffer(name_);
    1038             : }
    1039             : 
    1040             : //
    1041             : // Update the routing policy on the instance
    1042             : // 1. New policy is added
    1043             : // 2. Policy order changed
    1044             : // 3. Policy is removed
    1045             : // 4. Existing policy gets updated(terms in the policy got modified)
    1046             : // In any of the above cases, we call routing policy manager to re-evaluate the
    1047             : // routes in the BgpTables of this routing instance with new set of policies
    1048             : //
    1049           1 : void RoutingInstance::UpdateRoutingPolicyConfig() {
    1050           1 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1051           1 :     RoutingPolicyMgr *policy_mgr = server()->routing_policy_mgr();
    1052           1 :     if (policy_mgr->UpdateRoutingPolicyList(config_->routing_policy_list(),
    1053             :                                             routing_policies())) {
    1054             :         // Let RoutingPolicyMgr handle update of routing policy on the instance
    1055           0 :         policy_mgr->ApplyRoutingPolicy(this);
    1056             :     }
    1057           1 : }
    1058             : 
    1059         201 : void RoutingInstance::ProcessServiceChainConfig() {
    1060         201 :     if (is_master_)
    1061          40 :         return;
    1062             : 
    1063             :     /**
    1064             :       * If any VN (both internal and non-internal) is connnected to an internal
    1065             :       * VN via a service-chain, we will create a service chain for EVPN address
    1066             :       * family as well so that we can re-originate routes from the internal VN
    1067             :       * RI's EVPN table.
    1068             :       * For other cases (any VN communicating with a non-internal VN via service
    1069             :       * chain), we do not need a service chain to watch the EVPN table.
    1070             :       * Schema-transformer needs to make sure to add the service chain config for
    1071             :       * EVPN address family to all VNs which need to communicate via a
    1072             :       * service-chain with an internal VN.
    1073             :       */
    1074             :     vector<SCAddress::Family> families = list_of
    1075         161 :         (SCAddress::INET) (SCAddress::INET6)
    1076         161 :         (SCAddress::EVPN) (SCAddress::EVPN6);
    1077             : 
    1078        1449 :     BOOST_FOREACH(SCAddress::Family family, families) {
    1079             :         const ServiceChainConfig *sc_config =
    1080         644 :             config_ ? config_->service_chain_info(family) : NULL;
    1081         644 :         IServiceChainMgr *manager = server_->service_chain_mgr(family);
    1082         644 :         if (sc_config && !sc_config->routing_instance.empty()) {
    1083           0 :             manager->LocateServiceChain(this, *sc_config);
    1084             :         } else {
    1085         644 :             manager->StopServiceChain(this);
    1086             :         }
    1087             :     }
    1088         161 : }
    1089             : 
    1090         100 : void RoutingInstance::ProcessStaticRouteConfig() {
    1091         100 :     if (is_master_)
    1092          20 :         return;
    1093             : 
    1094          80 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1095         400 :     BOOST_FOREACH(Address::Family family, families) {
    1096         160 :         IStaticRouteMgr *manager = static_route_mgr(family);
    1097         160 :         if (!manager && !config_->static_routes(family).empty())
    1098           0 :             manager = LocateStaticRouteMgr(family);
    1099         160 :         if (manager)
    1100           0 :             manager->ProcessStaticRouteConfig();
    1101             :     }
    1102          80 : }
    1103             : 
    1104           1 : void RoutingInstance::UpdateStaticRouteConfig() {
    1105           1 :     if (is_master_)
    1106           0 :         return;
    1107             : 
    1108           1 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1109           5 :     BOOST_FOREACH(Address::Family family, families) {
    1110           2 :         IStaticRouteMgr *manager = static_route_mgr(family);
    1111           2 :         if (!manager && !config_->static_routes(family).empty())
    1112           0 :             manager = LocateStaticRouteMgr(family);
    1113           2 :         if (manager)
    1114           0 :             manager->UpdateStaticRouteConfig();
    1115             :     }
    1116           1 : }
    1117             : 
    1118         100 : void RoutingInstance::FlushStaticRouteConfig() {
    1119         100 :     if (is_master_)
    1120          20 :         return;
    1121             : 
    1122          80 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1123         400 :     BOOST_FOREACH(Address::Family family, families) {
    1124         160 :         IStaticRouteMgr *manager = static_route_mgr(family);
    1125         160 :         if (manager)
    1126           0 :             manager->FlushStaticRouteConfig();
    1127             :     }
    1128          80 : }
    1129             : 
    1130           0 : void RoutingInstance::UpdateAllStaticRoutes() {
    1131           0 :     if (is_master_)
    1132           0 :         return;
    1133             : 
    1134           0 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1135           0 :     BOOST_FOREACH(Address::Family family, families) {
    1136           0 :         IStaticRouteMgr *manager = static_route_mgr(family);
    1137           0 :         if (manager)
    1138           0 :             manager->UpdateAllRoutes();
    1139             :     }
    1140           0 : }
    1141             : 
    1142         100 : void RoutingInstance::ProcessRouteAggregationConfig() {
    1143         100 :     if (is_master_)
    1144          20 :         return;
    1145             : 
    1146          80 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1147         400 :     BOOST_FOREACH(Address::Family family, families) {
    1148         160 :         IRouteAggregator *aggregator = route_aggregator(family);
    1149         160 :         if (!aggregator && !config_->aggregate_routes(family).empty())
    1150           0 :             aggregator = LocateRouteAggregator(family);
    1151         160 :         if (aggregator)
    1152           0 :             aggregator->ProcessAggregateRouteConfig();
    1153             :     }
    1154          80 : }
    1155             : 
    1156           1 : void RoutingInstance::UpdateRouteAggregationConfig() {
    1157           1 :     if (is_master_)
    1158           0 :         return;
    1159             : 
    1160           1 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1161           5 :     BOOST_FOREACH(Address::Family family, families) {
    1162           2 :         IRouteAggregator *aggregator = route_aggregator(family);
    1163           2 :         if (!aggregator && !config_->aggregate_routes(family).empty())
    1164           0 :             aggregator = LocateRouteAggregator(family);
    1165           2 :         if (aggregator)
    1166           0 :             aggregator->UpdateAggregateRouteConfig();
    1167             :     }
    1168           1 : }
    1169             : 
    1170         100 : void RoutingInstance::FlushRouteAggregationConfig() {
    1171         100 :     if (is_master_)
    1172          20 :         return;
    1173             : 
    1174          80 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1175         400 :     BOOST_FOREACH(Address::Family family, families) {
    1176         160 :         IRouteAggregator *aggregator = route_aggregator(family);
    1177         160 :         if (aggregator)
    1178           0 :             aggregator->FlushAggregateRouteConfig();
    1179             :     }
    1180          80 : }
    1181             : 
    1182          60 : void RoutingInstance::DeleteMvpnRTargetRoute(as_t asn, Ip4Address old_ip) {
    1183          60 :     if (asn == 0)
    1184          40 :         return;
    1185          40 :     string id_str = "target:" + old_ip.to_string() + ":0";
    1186          20 :     RouteTarget rtarget = RouteTarget::FromString(id_str);
    1187          20 :     DeleteRTargetRoute(asn, rtarget);
    1188          20 : }
    1189             : 
    1190          40 : void RoutingInstance::AddMvpnRTargetRoute(as_t asn) {
    1191          40 :     if (asn == 0)
    1192          20 :         return;
    1193          20 :     const Ip4Address server_ip(server()->bgp_identifier());
    1194          40 :     string id_str = "target:" + server_ip.to_string() + ":0";
    1195          20 :     RouteTarget rtarget = RouteTarget::FromString(id_str);
    1196          20 :     AddRTargetRoute(asn, rtarget);
    1197          20 : }
    1198             : 
    1199         100 : void RoutingInstance::ProcessConfig() {
    1200         100 :     RoutingInstanceInfo info = GetDataCollection("");
    1201             : 
    1202             :     // Initialize virtual network info.
    1203         100 :     virtual_network_ = config_->virtual_network();
    1204         100 :     virtual_network_index_ = config_->virtual_network_index();
    1205         100 :     virtual_network_allow_transit_ = config_->virtual_network_allow_transit();
    1206         100 :     virtual_network_pbb_evpn_enable_ =
    1207         100 :         config_->virtual_network_pbb_evpn_enable();
    1208         100 :     vxlan_id_ = config_->vxlan_id();
    1209         100 :     routing_instance_vxlan_ = config_->routing_instance_vxlan();
    1210             : 
    1211             :     // Always subscribe (using RTF) for RTs of PNF service chain instances.
    1212         100 :     always_subscribe_ = config_->has_pnf();
    1213             : 
    1214         100 :     vector<string> import_rt, export_rt;
    1215        1054 :     BOOST_FOREACH(string irt, config_->import_list()) {
    1216         476 :         error_code error;
    1217         476 :         RouteTarget rt = RouteTarget::FromString(irt, &error);
    1218         476 :         if (!error) {
    1219         476 :             import_.insert(rt);
    1220         477 :             import_rt.push_back(irt);
    1221             :         }
    1222         477 :     }
    1223         732 :     BOOST_FOREACH(string ert, config_->export_list()) {
    1224         315 :         error_code error;
    1225         315 :         RouteTarget rt = RouteTarget::FromString(ert, &error);
    1226         317 :         if (!error) {
    1227         317 :             export_.insert(rt);
    1228         317 :             export_rt.push_back(ert);
    1229             :         }
    1230         316 :     }
    1231         100 :     RTINSTANCE_LOG(Update, this,
    1232             :                 SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL,
    1233             :                 import_rt, export_rt, this->virtual_network_index());
    1234             : 
    1235         100 :     if (import_rt.size())
    1236          80 :         info.set_add_import_rt(import_rt);
    1237         100 :     if (export_rt.size())
    1238          80 :         info.set_add_export_rt(export_rt);
    1239         100 :     if (import_rt.size() || export_rt.size())
    1240          80 :         ROUTING_INSTANCE_COLLECTOR_INFO(info);
    1241             : 
    1242             :     // Create BGP Table
    1243         100 :     if (name_ == BgpConfigManager::kMasterInstance) {
    1244          20 :         assert(mgr_->count() == 0);
    1245          20 :         is_master_ = true;
    1246             : 
    1247          20 :         LocatePeerManager();
    1248          20 :         VpnTableCreate(Address::INETVPN);
    1249          20 :         VpnTableCreate(Address::INET6VPN);
    1250          20 :         VpnTableCreate(Address::ERMVPN);
    1251          20 :         VpnTableCreate(Address::MVPN);
    1252          20 :         VpnTableCreate(Address::EVPN);
    1253          20 :         RTargetTableCreate();
    1254             : 
    1255             :         BgpTable *table_inet = static_cast<BgpTable *>(
    1256          20 :             server_->database()->CreateTable("inet.0"));
    1257          20 :         assert(table_inet);
    1258          20 :         AddTable(table_inet);
    1259             : 
    1260             :         BgpTable *table_inetmpls = static_cast<BgpTable *>(
    1261          20 :             server_->database()->CreateTable("inet.3"));
    1262          20 :         assert(table_inetmpls);
    1263          20 :         AddTable(table_inetmpls);
    1264             : 
    1265             :         BgpTable *table_inet6 = static_cast<BgpTable *>(
    1266          20 :             server_->database()->CreateTable("inet6.0"));
    1267          20 :         assert(table_inet6);
    1268          20 :         AddTable(table_inet6);
    1269             :     } else {
    1270             :         // Create foo.family.0.
    1271             :         // Create path-resolver in INET, INET6 and EVPN VRF tables to enable
    1272             :         // nh_reachability check for fast convergence.
    1273          80 :         BgpTable *inet_table = VrfTableCreate(Address::INET, Address::INETVPN);
    1274          80 :         inet_table->LocatePathResolver();
    1275             : 
    1276             :         BgpTable *inet6_table =
    1277          80 :             VrfTableCreate(Address::INET6, Address::INET6VPN);
    1278          80 :         inet6_table->LocatePathResolver();
    1279             : 
    1280          80 :         VrfTableCreate(Address::ERMVPN, Address::ERMVPN);
    1281             : 
    1282          80 :         BgpTable *evpn_table = VrfTableCreate(Address::EVPN, Address::EVPN);
    1283          80 :         evpn_table->LocatePathResolver();
    1284             : 
    1285          80 :         BgpTable *table = VrfTableCreate(Address::MVPN, Address::MVPN);
    1286             : 
    1287             :         // Create path-resolver in mvpn table.
    1288          80 :         table->LocatePathResolver();
    1289             :     }
    1290             : 
    1291         100 :     ProcessServiceChainConfig();
    1292         100 :     ProcessStaticRouteConfig();
    1293         100 :     ProcessRouteAggregationConfig();
    1294         100 :     ProcessRoutingPolicyConfig();
    1295         100 : }
    1296             : 
    1297          41 : void RoutingInstance::UpdateConfig(const BgpInstanceConfig *cfg) {
    1298          41 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1299             : 
    1300             :     // This is a noop in production code. However unit tests may pass a
    1301             :     // new object.
    1302          41 :     config_ = cfg;
    1303             : 
    1304             :     // Always subscribe (using RTF) for RTs of PNF service chain instances.
    1305          41 :     always_subscribe_ = config_->has_pnf();
    1306             : 
    1307             :     // Figure out if there's a significant configuration change that requires
    1308             :     // notifying routes to all listeners.
    1309          41 :     bool notify_routes = false;
    1310          41 :     if (virtual_network_allow_transit_ != cfg->virtual_network_allow_transit())
    1311           0 :         notify_routes = true;
    1312          41 :     if (virtual_network_pbb_evpn_enable_ !=
    1313          41 :         cfg->virtual_network_pbb_evpn_enable())
    1314           0 :         notify_routes = true;
    1315          41 :     if (virtual_network_ != cfg->virtual_network())
    1316           0 :         notify_routes = true;
    1317          41 :     if (virtual_network_index_ != cfg->virtual_network_index())
    1318           0 :         notify_routes = true;
    1319             : 
    1320             :     // Trigger notification of all routes in each table.
    1321          41 :     if (notify_routes) {
    1322           0 :         BOOST_FOREACH(RouteTableList::value_type &entry, vrf_tables_by_name_) {
    1323           0 :             BgpTable *table = entry.second;
    1324           0 :             table->NotifyAllEntries();
    1325             :         }
    1326             :     }
    1327             : 
    1328             :     // Update all static routes so that they reflect the new OriginVn.
    1329          41 :     if (virtual_network_index_ != cfg->virtual_network_index())
    1330           0 :         UpdateAllStaticRoutes();
    1331             : 
    1332          41 :     string prev_vn_name = GetVirtualNetworkName();
    1333             : 
    1334             :     // Update virtual network info.
    1335          41 :     virtual_network_ = cfg->virtual_network();
    1336             : 
    1337             :     // Recreate instance stats' UVE, if its key: virtual_network is modified.
    1338          41 :     if (prev_vn_name != GetVirtualNetworkName()) {
    1339           0 :         mgr_->DeleteVirtualNetworkMapping(prev_vn_name, name_);
    1340           0 :         mgr_->CreateVirtualNetworkMapping(GetVirtualNetworkName(), name_);
    1341             :     }
    1342             : 
    1343          41 :     virtual_network_index_ = cfg->virtual_network_index();
    1344          41 :     virtual_network_allow_transit_ = cfg->virtual_network_allow_transit();
    1345          41 :     virtual_network_pbb_evpn_enable_ = cfg->virtual_network_pbb_evpn_enable();
    1346          41 :     vxlan_id_ = cfg->vxlan_id();
    1347          41 :     routing_instance_vxlan_ = cfg->routing_instance_vxlan();
    1348             : 
    1349             :     // Master routing instance doesn't have import & export list
    1350             :     // Master instance imports and exports all RT
    1351          41 :     if (IsMasterRoutingInstance())
    1352          40 :         return;
    1353             : 
    1354           1 :     RouteTargetList future_import;
    1355           1 :     vector<string> add_import_rt, remove_import_rt;
    1356          13 :     BOOST_FOREACH(const string &rtarget_str, cfg->import_list()) {
    1357           6 :         error_code error;
    1358           6 :         RouteTarget rt = RouteTarget::FromString(rtarget_str, &error);
    1359           6 :         if (!error)
    1360           6 :             future_import.insert(rt);
    1361             :     }
    1362           1 :     set_synchronize(&import_, &future_import,
    1363             :         boost::bind(&RoutingInstance::AddRouteTarget, this, true,
    1364             :             &add_import_rt, _1),
    1365             :         boost::bind(&RoutingInstance::DeleteRouteTarget, this, true,
    1366             :             &remove_import_rt, _1));
    1367             : 
    1368           1 :     RouteTargetList future_export;
    1369           1 :     vector<string> add_export_rt, remove_export_rt;
    1370           9 :     BOOST_FOREACH(const string &rtarget_str, cfg->export_list()) {
    1371           4 :         error_code error;
    1372           4 :         RouteTarget rt = RouteTarget::FromString(rtarget_str, &error);
    1373           4 :         if (!error)
    1374           4 :             future_export.insert(rt);
    1375             :     }
    1376           1 :     set_synchronize(&export_, &future_export,
    1377             :         boost::bind(&RoutingInstance::AddRouteTarget, this, false,
    1378             :             &add_export_rt, _1),
    1379             :         boost::bind(&RoutingInstance::DeleteRouteTarget, this, false,
    1380             :             &remove_export_rt, _1));
    1381             : 
    1382           1 :     RoutingInstanceInfo info = GetDataCollection("");
    1383           1 :     if (add_import_rt.size())
    1384           1 :         info.set_add_import_rt(add_import_rt);
    1385           1 :     if (remove_import_rt.size())
    1386           0 :         info.set_remove_import_rt(remove_import_rt);
    1387           1 :     if (add_export_rt.size())
    1388           1 :         info.set_add_export_rt(add_export_rt);
    1389           1 :     if (remove_export_rt.size())
    1390           0 :         info.set_remove_export_rt(remove_export_rt);
    1391           1 :     if (add_import_rt.size() || remove_import_rt.size() ||
    1392           1 :         add_export_rt.size() || remove_export_rt.size())
    1393           1 :         ROUTING_INSTANCE_COLLECTOR_INFO(info);
    1394             : 
    1395           1 :     ProcessServiceChainConfig();
    1396           1 :     UpdateStaticRouteConfig();
    1397           1 :     UpdateRouteAggregationConfig();
    1398           1 :     UpdateRoutingPolicyConfig();
    1399          41 : }
    1400             : 
    1401         100 : void RoutingInstance::ClearConfig() {
    1402         100 :     CHECK_CONCURRENCY("bgp::Config");
    1403         100 :     config_ = NULL;
    1404         100 : }
    1405             : 
    1406         100 : void RoutingInstance::ManagedDelete() {
    1407             :     // RoutingInstanceMgr logs the delete for non-master instances.
    1408         100 :     if (IsMasterRoutingInstance()) {
    1409          20 :         RTINSTANCE_LOG(Delete, this,
    1410             :             SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL);
    1411             :     }
    1412         100 :     deleter_->Delete();
    1413         100 : }
    1414             : 
    1415         100 : void RoutingInstance::Shutdown() {
    1416         100 :     CHECK_CONCURRENCY("bgp::Config");
    1417             : 
    1418         100 :     RTINSTANCE_LOG(Shutdown, this,
    1419             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL);
    1420             : 
    1421         100 :     ClearConfig();
    1422         100 :     FlushAllRTargetRoutes(server_->local_autonomous_system());
    1423         100 :     if (is_master_) {
    1424          20 :         const Ip4Address old_identifier(server()->bgp_identifier());
    1425          20 :         DeleteMvpnRTargetRoute(server_->local_autonomous_system(),
    1426             :                 old_identifier);
    1427             :     }
    1428         100 :     ClearRouteTarget();
    1429             : 
    1430         100 :     ProcessServiceChainConfig();
    1431         100 :     FlushStaticRouteConfig();
    1432         100 :     FlushRouteAggregationConfig();
    1433         100 : }
    1434             : 
    1435         100 : bool RoutingInstance::MayDelete() const {
    1436         100 :     return true;
    1437             : }
    1438             : 
    1439         632 : LifetimeActor *RoutingInstance::deleter() {
    1440         632 :     return deleter_.get();
    1441             : }
    1442             : 
    1443       29718 : const LifetimeActor *RoutingInstance::deleter() const {
    1444       29718 :     return deleter_.get();
    1445             : }
    1446             : 
    1447       29719 : bool RoutingInstance::deleted() const {
    1448       29719 :     return deleter()->IsDeleted();
    1449             : }
    1450             : 
    1451        7001 : const string RoutingInstance::GetVirtualNetworkName() const {
    1452        7001 :     if (!virtual_network_.empty())
    1453           0 :         return virtual_network_;
    1454        7001 :     size_t pos = name_.rfind(':');
    1455        7001 :     if (pos == string::npos) {
    1456        5205 :         return name_;
    1457             :     } else {
    1458        1796 :         return name_.substr(0, pos);
    1459             :     }
    1460             : }
    1461             : 
    1462      245346 : int RoutingInstance::virtual_network_index() const {
    1463      245346 :     return virtual_network_index_;
    1464             : }
    1465             : 
    1466           0 : bool RoutingInstance::virtual_network_allow_transit() const {
    1467           0 :     return virtual_network_allow_transit_;
    1468             : }
    1469             : 
    1470           0 : bool RoutingInstance::virtual_network_pbb_evpn_enable() const {
    1471           0 :     return virtual_network_pbb_evpn_enable_;
    1472             : }
    1473             : 
    1474           0 : int RoutingInstance::vxlan_id() const {
    1475           0 :     return vxlan_id_;
    1476             : }
    1477             : 
    1478         400 : void RoutingInstance::ClearFamilyRouteTarget(Address::Family vrf_family,
    1479             :                                              Address::Family vpn_family) {
    1480         400 :     BgpTable *table = GetTable(vrf_family);
    1481         400 :     if (table) {
    1482         400 :         RoutePathReplicator *replicator = server_->replicator(vpn_family);
    1483        5200 :         BOOST_FOREACH(RouteTarget rt, import_) {
    1484        2400 :             replicator->Leave(table, rt, true);
    1485             :         }
    1486        3600 :         BOOST_FOREACH(RouteTarget rt, export_) {
    1487        1600 :             replicator->Leave(table, rt, false);
    1488             :         }
    1489             :     }
    1490         400 : }
    1491             : 
    1492          20 : void RoutingInstance::AddRTargetRoute(uint32_t asn,
    1493             :     const RouteTarget &rtarget) {
    1494          20 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1495             : 
    1496          20 :     RTargetPrefix prefix(asn, rtarget);
    1497          20 :     RTargetRoute rt_key(prefix);
    1498             : 
    1499          20 :     RoutingInstance *master = mgr_->GetDefaultRoutingInstance();
    1500          20 :     BgpTable *table = master->GetTable(Address::RTARGET);
    1501             :     DBTablePartition *tbl_partition =
    1502          20 :         static_cast<DBTablePartition *>(table->GetTablePartition(0));
    1503             : 
    1504          20 :     std::scoped_lock lock(mgr_->mutex());
    1505             :     RTargetRoute *route =
    1506          20 :         static_cast<RTargetRoute *>(tbl_partition->Find(&rt_key));
    1507          20 :     if (!route) {
    1508          20 :         route = new RTargetRoute(prefix);
    1509          20 :         tbl_partition->Add(route);
    1510             :     } else {
    1511           0 :         route->ClearDelete();
    1512             :     }
    1513             : 
    1514          20 :     if (route->FindPath(BgpPath::Local, index_))
    1515           0 :         return;
    1516             : 
    1517          20 :     BgpAttrSpec attr_spec;
    1518          20 :     BgpAttrNextHop nexthop(server_->bgp_identifier());
    1519          20 :     attr_spec.push_back(&nexthop);
    1520          20 :     BgpAttrOrigin origin(BgpAttrOrigin::IGP);
    1521          20 :     attr_spec.push_back(&origin);
    1522          20 :     BgpAttrPtr attr = server_->attr_db()->Locate(attr_spec);
    1523             : 
    1524          20 :     BgpPath *path = new BgpPath(index_, BgpPath::Local, attr);
    1525          20 :     route->InsertPath(path);
    1526          20 :     tbl_partition->Notify(route);
    1527          20 :     BGP_LOG_ROUTE(table, static_cast<IPeer *>(NULL),
    1528             :         route, "Insert Local path with path id " << index_);
    1529          20 : }
    1530             : 
    1531         500 : void RoutingInstance::DeleteRTargetRoute(as_t asn,
    1532             :     const RouteTarget &rtarget) {
    1533         500 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1534             : 
    1535         500 :     if (asn == 0)
    1536         480 :         return;
    1537             : 
    1538         500 :     RTargetPrefix prefix(asn, rtarget);
    1539         500 :     RTargetRoute rt_key(prefix);
    1540             : 
    1541         500 :     RoutingInstance *master = mgr_->GetDefaultRoutingInstance();
    1542         500 :     BgpTable *table = master->GetTable(Address::RTARGET);
    1543             :     DBTablePartition *tbl_partition =
    1544         500 :         static_cast<DBTablePartition *>(table->GetTablePartition(0));
    1545             : 
    1546         500 :     std::scoped_lock lock(mgr_->mutex());
    1547             :     RTargetRoute *route =
    1548         500 :         static_cast<RTargetRoute *>(tbl_partition->Find(&rt_key));
    1549         500 :     if (!route || !route->RemovePath(BgpPath::Local, index_))
    1550         480 :         return;
    1551             : 
    1552          20 :     BGP_LOG_ROUTE(table, static_cast<IPeer *>(NULL),
    1553             :         route, "Delete Local path with path id " << index_);
    1554          20 :     if (!route->HasPaths()) {
    1555          20 :         tbl_partition->Delete(route);
    1556             :     } else {
    1557           0 :         tbl_partition->Notify(route);
    1558             :     }
    1559         980 : }
    1560             : 
    1561         140 : void RoutingInstance::InitAllRTargetRoutes(as_t asn) {
    1562         140 :     if (is_master_)
    1563          60 :         return;
    1564             : 
    1565          80 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1566        1034 :     BOOST_FOREACH(RouteTarget rtarget, import_) {
    1567         477 :         if (asn != 0 && always_subscribe_)
    1568           0 :             AddRTargetRoute(asn, rtarget);
    1569             :     }
    1570             : }
    1571             : 
    1572         140 : void RoutingInstance::FlushAllRTargetRoutes(as_t asn) {
    1573         140 :     if (is_master_)
    1574          60 :         return;
    1575             : 
    1576          80 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1577        1040 :     BOOST_FOREACH(RouteTarget rtarget, import_) {
    1578         480 :         DeleteRTargetRoute(asn, rtarget);
    1579             :     }
    1580             : }
    1581             : 
    1582          20 : void RoutingInstance::ProcessIdentifierUpdate(as_t asn) {
    1583          20 :     FlushAllRTargetRoutes(asn);
    1584          20 :     InitAllRTargetRoutes(asn);
    1585          20 :     rd_.reset(new RouteDistinguisher(server_->bgp_identifier(), index_));
    1586          20 : }
    1587             : 
    1588           6 : void RoutingInstance::AddRouteTarget(bool import,
    1589             :     vector<string> *change_list, RouteTargetList::const_iterator it) {
    1590           6 :     BgpTable *ermvpn_table = GetTable(Address::ERMVPN);
    1591             :     RoutePathReplicator *ermvpn_replicator =
    1592           6 :         server_->replicator(Address::ERMVPN);
    1593           6 :     BgpTable *mvpn_table = GetTable(Address::MVPN);
    1594             :     RoutePathReplicator *mvpn_replicator =
    1595           6 :         server_->replicator(Address::MVPN);
    1596           6 :     BgpTable *evpn_table = GetTable(Address::EVPN);
    1597             :     RoutePathReplicator *evpn_replicator =
    1598           6 :         server_->replicator(Address::EVPN);
    1599           6 :     BgpTable *inet_table = GetTable(Address::INET);
    1600             :     RoutePathReplicator *inetvpn_replicator =
    1601           6 :         server_->replicator(Address::INETVPN);
    1602           6 :     BgpTable *inet6_table = GetTable(Address::INET6);
    1603             :     RoutePathReplicator *inet6vpn_replicator =
    1604           6 :         server_->replicator(Address::INET6VPN);
    1605             : 
    1606           6 :     change_list->push_back(it->ToString());
    1607           6 :     if (import) {
    1608           3 :         import_.insert(*it);
    1609           3 :         if (server_->local_autonomous_system() != 0 && always_subscribe_)
    1610           0 :             AddRTargetRoute(server_->local_autonomous_system(), *it);
    1611             :     } else {
    1612           3 :         export_.insert(*it);
    1613             :     }
    1614             : 
    1615           6 :     ermvpn_replicator->Join(ermvpn_table, *it, import);
    1616           6 :     mvpn_replicator->Join(mvpn_table, *it, import);
    1617           6 :     evpn_replicator->Join(evpn_table, *it, import);
    1618           6 :     inetvpn_replicator->Join(inet_table, *it, import);
    1619           6 :     inet6vpn_replicator->Join(inet6_table, *it, import);
    1620           6 : }
    1621             : 
    1622           0 : void RoutingInstance::DeleteRouteTarget(bool import,
    1623             :     vector<string> *change_list, RouteTargetList::iterator it) {
    1624           0 :     BgpTable *ermvpn_table = GetTable(Address::ERMVPN);
    1625             :     RoutePathReplicator *ermvpn_replicator =
    1626           0 :         server_->replicator(Address::ERMVPN);
    1627           0 :     BgpTable *mvpn_table = GetTable(Address::MVPN);
    1628             :     RoutePathReplicator *mvpn_replicator =
    1629           0 :         server_->replicator(Address::MVPN);
    1630           0 :     BgpTable *evpn_table = GetTable(Address::EVPN);
    1631             :     RoutePathReplicator *evpn_replicator =
    1632           0 :         server_->replicator(Address::EVPN);
    1633           0 :     BgpTable *inet_table = GetTable(Address::INET);
    1634             :     RoutePathReplicator *inetvpn_replicator =
    1635           0 :         server_->replicator(Address::INETVPN);
    1636           0 :     BgpTable *inet6_table = GetTable(Address::INET6);
    1637             :     RoutePathReplicator *inet6vpn_replicator =
    1638           0 :         server_->replicator(Address::INET6VPN);
    1639             : 
    1640           0 :     ermvpn_replicator->Leave(ermvpn_table, *it, import);
    1641           0 :     mvpn_replicator->Leave(mvpn_table, *it, import);
    1642           0 :     evpn_replicator->Leave(evpn_table, *it, import);
    1643           0 :     inetvpn_replicator->Leave(inet_table, *it, import);
    1644           0 :     inet6vpn_replicator->Leave(inet6_table, *it, import);
    1645             : 
    1646           0 :     change_list->push_back(it->ToString());
    1647           0 :     if (import) {
    1648           0 :         DeleteRTargetRoute(server_->local_autonomous_system(), *it);
    1649           0 :         import_.erase(it);
    1650             :     } else {
    1651           0 :         export_.erase(it);
    1652             :     }
    1653           0 : }
    1654             : 
    1655         100 : void RoutingInstance::ClearRouteTarget() {
    1656         100 :     CHECK_CONCURRENCY("bgp::Config");
    1657         100 :     if (IsMasterRoutingInstance()) {
    1658          20 :         return;
    1659             :     }
    1660             : 
    1661          80 :     ClearFamilyRouteTarget(Address::INET, Address::INETVPN);
    1662          80 :     ClearFamilyRouteTarget(Address::INET6, Address::INET6VPN);
    1663          80 :     ClearFamilyRouteTarget(Address::ERMVPN, Address::ERMVPN);
    1664          80 :     ClearFamilyRouteTarget(Address::MVPN, Address::MVPN);
    1665          80 :     ClearFamilyRouteTarget(Address::EVPN, Address::EVPN);
    1666             : 
    1667          80 :     import_.clear();
    1668          80 :     export_.clear();
    1669             : }
    1670             : 
    1671          20 : BgpTable *RoutingInstance::RTargetTableCreate() {
    1672             :     BgpTable *rtargettbl = static_cast<BgpTable *>(
    1673          20 :         server_->database()->CreateTable("bgp.rtarget.0"));
    1674          20 :     RTINSTANCE_LOG_TABLE(Create, this, rtargettbl, SandeshLevel::SYS_DEBUG,
    1675             :                          RTINSTANCE_LOG_FLAG_ALL);
    1676          20 :     AddTable(rtargettbl);
    1677          20 :     return rtargettbl;
    1678             : }
    1679             : 
    1680         100 : BgpTable *RoutingInstance::VpnTableCreate(Address::Family vpn_family) {
    1681         100 :     string table_name = GetTableName(name(), vpn_family);
    1682             :     BgpTable *table = static_cast<BgpTable *>(
    1683         100 :         server_->database()->CreateTable(table_name));
    1684         100 :     assert(table);
    1685             : 
    1686         100 :     AddTable(table);
    1687         100 :     RTINSTANCE_LOG_TABLE(Create, this, table, SandeshLevel::SYS_DEBUG,
    1688             :         RTINSTANCE_LOG_FLAG_ALL);
    1689         100 :     assert(server_->rtarget_group_mgr()->empty());
    1690         100 :     RoutePathReplicator *replicator = server_->replicator(vpn_family);
    1691         100 :     replicator->Initialize();
    1692         100 :     return table;
    1693         100 : }
    1694             : 
    1695         400 : BgpTable *RoutingInstance::VrfTableCreate(Address::Family vrf_family,
    1696             :     Address::Family vpn_family) {
    1697         400 :     string table_name = GetTableName(name(), vrf_family);
    1698             :     BgpTable *table = static_cast<BgpTable *>(
    1699         400 :         server_->database()->CreateTable(table_name));
    1700         400 :     assert(table);
    1701             : 
    1702         400 :     AddTable(table);
    1703         400 :     RTINSTANCE_LOG_TABLE(Create, this, table, SandeshLevel::SYS_DEBUG,
    1704             :         RTINSTANCE_LOG_FLAG_ALL);
    1705         400 :     RoutePathReplicator *replicator = server_->replicator(vpn_family);
    1706        5170 :     BOOST_FOREACH(RouteTarget rt, import_) {
    1707        2385 :         replicator->Join(table, rt, true);
    1708             :     }
    1709        3570 :     BOOST_FOREACH(RouteTarget rt, export_) {
    1710        1585 :         replicator->Join(table, rt, false);
    1711             :     }
    1712         400 :     return table;
    1713         400 : }
    1714             : 
    1715         580 : void RoutingInstance::AddTable(BgpTable *tbl) {
    1716         580 :     vrf_tables_by_name_.insert(make_pair(tbl->name(), tbl));
    1717         580 :     vrf_tables_by_family_.insert(make_pair(tbl->family(), tbl));
    1718         580 :     tbl->set_routing_instance(this);
    1719         580 :     RoutingInstanceInfo info = GetDataCollection("Add");
    1720         580 :     info.set_family(Address::FamilyToString(tbl->family()));
    1721         580 :     ROUTING_INSTANCE_COLLECTOR_INFO(info);
    1722         580 : }
    1723             : 
    1724         580 : void RoutingInstance::RemoveTable(BgpTable *tbl) {
    1725         580 :     RoutingInstanceInfo info = GetDataCollection("Remove");
    1726         580 :     info.set_family(Address::FamilyToString(tbl->family()));
    1727         580 :     vrf_tables_by_name_.erase(tbl->name());
    1728         580 :     vrf_tables_by_family_.erase(tbl->family());
    1729         580 :     ROUTING_INSTANCE_COLLECTOR_INFO(info);
    1730         580 : }
    1731             : 
    1732             : //
    1733             : // Concurrency: BGP Config task
    1734             : //
    1735             : // Remove the table from the map and delete the table data structure
    1736             : //
    1737         580 : void RoutingInstance::DestroyDBTable(DBTable *dbtable) {
    1738         580 :     CHECK_CONCURRENCY("bgp::Config");
    1739             : 
    1740         580 :     BgpTable *table = static_cast<BgpTable *>(dbtable);
    1741             : 
    1742         580 :     RTINSTANCE_LOG_TABLE(Destroy, this, table,
    1743             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL);
    1744             : 
    1745             :     // Remove this table from various data structures
    1746         580 :     server_->database()->RemoveTable(table);
    1747         580 :     RemoveTable(table);
    1748             : 
    1749             :     // Make sure that there are no routes left in this table
    1750         580 :     assert(table->Size() == 0);
    1751             : 
    1752         580 :     delete table;
    1753         580 : }
    1754             : 
    1755         500 : string RoutingInstance::GetTableName(string instance_name,
    1756             :     Address::Family fmly) {
    1757         500 :     string table_name;
    1758         500 :     if (instance_name == BgpConfigManager::kMasterInstance) {
    1759         100 :         if ((fmly == Address::INET) || (fmly == Address::INET6)) {
    1760           0 :             table_name = Address::FamilyToTableString(fmly) + ".0";
    1761         100 :         } else if (fmly == Address::INETMPLS) {
    1762           0 :             table_name = Address::FamilyToTableString(fmly) + ".3";
    1763             :         } else {
    1764         100 :             table_name = "bgp." + Address::FamilyToTableString(fmly) + ".0";
    1765             :         }
    1766             :     } else {
    1767             :         table_name =
    1768         400 :             instance_name + "." + Address::FamilyToTableString(fmly) + ".0";
    1769             :     }
    1770         500 :     return table_name;
    1771           0 : }
    1772             : 
    1773       16117 : BgpTable *RoutingInstance::GetTable(Address::Family fmly) {
    1774       16117 :     RouteTableFamilyList::const_iterator loc = vrf_tables_by_family_.find(fmly);
    1775       16115 :     return (loc != vrf_tables_by_family_.end() ? loc->second : NULL);
    1776             : }
    1777             : 
    1778           0 : const BgpTable *RoutingInstance::GetTable(Address::Family fmly) const {
    1779           0 :     RouteTableFamilyList::const_iterator loc = vrf_tables_by_family_.find(fmly);
    1780           0 :     return (loc != vrf_tables_by_family_.end() ? loc->second : NULL);
    1781             : }
    1782             : 
    1783           0 : string RoutingInstance::GetVrfFromTableName(const string table) {
    1784           0 :     static set<string> master_tables = list_of("inet.0")("inet.3")("inet6.0");
    1785             :     static set<string> vpn_tables =
    1786           0 :         list_of("bgp.l3vpn.0")("bgp.ermvpn.0")("bgp.evpn.0")("bgp.rtarget.0")
    1787           0 :                 ("bgp.l3vpn-inet6.0")("bgp.mvpn.0");
    1788             : 
    1789           0 :     if (master_tables.find(table) != master_tables.end())
    1790           0 :         return BgpConfigManager::kMasterInstance;
    1791           0 :     if (vpn_tables.find(table) != vpn_tables.end())
    1792           0 :         return BgpConfigManager::kMasterInstance;
    1793             : 
    1794           0 :     size_t pos1 = table.rfind('.');
    1795           0 :     if (pos1 == string::npos)
    1796           0 :         return "__unknown__";
    1797           0 :     size_t pos2 = table.rfind('.', pos1 - 1);
    1798           0 :     if (pos2 == string::npos)
    1799           0 :         return "__unknown__";
    1800             : 
    1801           0 :     return table.substr(0, pos2);
    1802             : }
    1803             : 
    1804         100 : void RoutingInstance::set_index(int index) {
    1805         100 :     index_ = index;
    1806         100 :     if (is_master_)
    1807          20 :         return;
    1808             : 
    1809          80 :     rd_.reset(new RouteDistinguisher(server_->bgp_identifier(), index));
    1810             : }
    1811             : 
    1812        1293 : RoutingInstanceInfo RoutingInstance::GetDataCollection(const char *operation) {
    1813        2586 :     RoutingInstanceInfo info;
    1814        1293 :     info.set_name(GetVirtualNetworkName());
    1815        1293 :     info.set_instance_name(name_);
    1816        1293 :     info.set_hostname(server_->localname());
    1817        1293 :     if (rd_.get()) info.set_route_distinguisher(rd_->ToString());
    1818        1293 :     if (operation) info.set_operation(operation);
    1819        1293 :     return info;
    1820           0 : }
    1821             : 
    1822             : //
    1823             : // Return true if one of the route targets in the ExtCommunity is in the
    1824             : // set of export RouteTargets for this RoutingInstance.
    1825             : //
    1826           0 : bool RoutingInstance::HasExportTarget(const ExtCommunity *extcomm) const {
    1827           0 :     if (!extcomm)
    1828           0 :         return false;
    1829             : 
    1830           0 :     BOOST_FOREACH(const ExtCommunity::ExtCommunityValue &value,
    1831             :                   extcomm->communities()) {
    1832           0 :         if (!ExtCommunity::is_route_target(value))
    1833           0 :             continue;
    1834           0 :         RouteTarget rtarget(value);
    1835           0 :         if (export_.find(rtarget) != export_.end())
    1836           0 :             return true;
    1837             :     }
    1838             : 
    1839           0 :     return false;
    1840             : }
    1841             : 
    1842             : // Return true if the route is a service-chain route
    1843       27378 : bool RoutingInstance::IsServiceChainRoute(const BgpRoute *route) const {
    1844       27378 :     const BgpTable *table = route->table();
    1845       27384 :     if (!table) {
    1846           0 :         return false;
    1847             :     }
    1848       27384 :     const BgpInstanceConfig *rt_config = this->config();
    1849       27382 :     if (!rt_config) {
    1850           0 :         return false;
    1851             :     }
    1852             :     SCAddress::Family sc_family =
    1853       27382 :         SCAddress::AddressFamilyToSCFamily(table->family());
    1854             :     const ServiceChainConfig *sc_config =
    1855       27382 :            rt_config->service_chain_info(sc_family);
    1856       27382 :     if (!sc_config) {
    1857       27382 :         return false;
    1858             :     }
    1859           0 :     return true;
    1860             : }
    1861             : 
    1862             : //
    1863             : // On given route/path apply the routing policy
    1864             : //    Called from
    1865             : //        * InsertPath [While adding the path for the first time]
    1866             : //        * While walking the routing table to apply updating routing policy
    1867             : //
    1868             : 
    1869       28342 : bool RoutingInstance::ProcessRoutingPolicy(const BgpRoute *route,
    1870             :                                            BgpPath *path) const {
    1871       28342 :     ExtCommunityPtr ext_community = path->GetOriginalAttr()->ext_community();
    1872       55742 :     if (path->IsReplicated() &&
    1873       55742 :             ext_community && ext_community->GetSubClusterId()) {
    1874             :         // If self sub-cluster id macthes with what is associated with the route
    1875             :         // then no need to apply policy.
    1876           0 :         if (route->SubClusterId() == ext_community->GetSubClusterId()) {
    1877           0 :             BGP_LOG_ROUTE(route->table(), static_cast<IPeer *>(path->GetPeer()),
    1878             :                     route, "Not applying policy since sub-cluster associated "
    1879             :                     "with path is same as that with route");
    1880           0 :             return true;
    1881             :         }
    1882             :     }
    1883             :     // Don't apply routing policy on secondary path for service chain route
    1884       28338 :     if (path->IsReplicated() && IsServiceChainRoute(route)) {
    1885           0 :         BGP_LOG_ROUTE(route->table(), static_cast<IPeer *>(path->GetPeer()),
    1886             :                 route, "Not applying policy for service-chain secondary "
    1887             :                 "routes");
    1888           0 :         return true;
    1889             :     }
    1890       28339 :     const RoutingPolicyMgr *policy_mgr = server()->routing_policy_mgr();
    1891             :     // Take snapshot of original attribute
    1892       28340 :     BgpAttr *out_attr = new BgpAttr(*(path->GetOriginalAttr()));
    1893       28352 :     BOOST_FOREACH(RoutingPolicyInfo info, routing_policies()) {
    1894           0 :         RoutingPolicyPtr policy = info.first;
    1895             :         // Process the routing policy on original attribute and prefix
    1896             :         // Update of the attribute based on routing policy action is done
    1897             :         // on the snapshot of original attribute passed to this function
    1898             :         RoutingPolicy::PolicyResult result =
    1899           0 :             policy_mgr->ExecuteRoutingPolicy(policy.get(), route,
    1900             :                                              path, out_attr);
    1901           0 :         if (result.first) {
    1902             :             // Hit a terminal policy
    1903           0 :             if (!result.second) {
    1904             :                 // Result of the policy is reject
    1905           0 :                 path->SetPolicyReject();
    1906           0 :             } else if (path->IsPolicyReject()) {
    1907             :                 // Result of the policy is Accept
    1908             :                 // Clear the reject flag is marked before
    1909           0 :                 path->ResetPolicyReject();
    1910             :             }
    1911           0 :             IPeer *peer = path->GetPeer();
    1912             :             // Process default tunnel encapsulation that may be configured per
    1913             :             // address family on the peer. 'peer' is not expected to be NULL
    1914             :             // except in unit tests.
    1915           0 :             if (peer) {
    1916           0 :                 peer->ProcessPathTunnelEncapsulation(path, out_attr,
    1917           0 :                     server_->extcomm_db(), route->table());
    1918             :             }
    1919           0 :             BgpAttrPtr modified_attr = server_->attr_db()->Locate(out_attr);
    1920             :             // Update the path with new set of attributes
    1921           0 :             path->SetAttr(modified_attr, path->GetOriginalAttr());
    1922           0 :             return result.second;
    1923           0 :         }
    1924           0 :     }
    1925             :     // After processing all the routing policy,,
    1926             :     // We are here means, all the routing policies have accepted the route
    1927       28330 :     IPeer *peer = path->GetPeer();
    1928       28329 :     if (peer) {
    1929       52580 :         peer->ProcessPathTunnelEncapsulation(path, out_attr,
    1930       26296 :             server_->extcomm_db(), route->table());
    1931             :     }
    1932       28340 :     BgpAttrPtr modified_attr = server_->attr_db()->Locate(out_attr);
    1933       28350 :     path->SetAttr(modified_attr, path->GetOriginalAttr());
    1934             :     // Clear the reject if marked so in past
    1935       28352 :     if (path->IsPolicyReject()) path->ResetPolicyReject();
    1936       28352 :     return true;
    1937       28352 : }
    1938             : 
    1939           0 : IStaticRouteMgr *RoutingInstance::LocateStaticRouteMgr(
    1940             :     Address::Family family) {
    1941           0 :     IStaticRouteMgr *manager = static_route_mgr(family);
    1942           0 :     if (manager)
    1943           0 :         return manager;
    1944           0 :     if (family == Address::INET) {
    1945           0 :         inet_static_route_mgr_.reset(
    1946           0 :             BgpStaticObjectFactory::Create<IStaticRouteMgr, Address::INET>(this));
    1947           0 :         return inet_static_route_mgr_.get();
    1948           0 :     } else if (family == Address::INET6) {
    1949           0 :         inet6_static_route_mgr_.reset(
    1950           0 :             BgpStaticObjectFactory::Create<IStaticRouteMgr, Address::INET6>(this));
    1951           0 :         return inet6_static_route_mgr_.get();
    1952             :     }
    1953           0 :     return NULL;
    1954             : }
    1955             : 
    1956           0 : IRouteAggregator *RoutingInstance::LocateRouteAggregator(
    1957             :     Address::Family family) {
    1958           0 :     IRouteAggregator *aggregator = route_aggregator(family);
    1959           0 :     if (aggregator)
    1960           0 :         return aggregator;
    1961           0 :     if (family == Address::INET) {
    1962           0 :         GetTable(family)->LocatePathResolver();
    1963           0 :         inet_route_aggregator_.reset(
    1964           0 :             BgpStaticObjectFactory::Create<IRouteAggregator, Address::INET>(this));
    1965           0 :         inet_route_aggregator_->Initialize();
    1966           0 :         return inet_route_aggregator_.get();
    1967           0 :     } else if (family == Address::INET6) {
    1968           0 :         GetTable(family)->LocatePathResolver();
    1969           0 :         inet6_route_aggregator_.reset(
    1970           0 :             BgpStaticObjectFactory::Create<IRouteAggregator, Address::INET6>(this));
    1971           0 :         inet6_route_aggregator_->Initialize();
    1972           0 :         return inet6_route_aggregator_.get();
    1973             :     }
    1974           0 :     return NULL;
    1975             : }
    1976             : 
    1977           0 : void RoutingInstance::DestroyRouteAggregator(Address::Family family) {
    1978           0 :     if (family == Address::INET) {
    1979           0 :         inet_route_aggregator_.reset();
    1980           0 :     } else if (family == Address::INET6) {
    1981           0 :         inet6_route_aggregator_.reset();
    1982             :     }
    1983           0 : }
    1984             : 
    1985             : // Check whether the route is aggregating route
    1986           0 : bool RoutingInstance::IsAggregateRoute(const BgpTable *table,
    1987             :                                        const BgpRoute *route) const {
    1988           0 :     if (!route_aggregator(table->family())) return false;
    1989           0 :     return route_aggregator(table->family())->IsAggregateRoute(route);
    1990             : }
    1991             : 
    1992             : // Check whether the route is contributing route to aggregate route
    1993       56337 : bool RoutingInstance::IsContributingRoute(const BgpTable *table,
    1994             :                                           const BgpRoute *route) const {
    1995       56337 :     if (!route_aggregator(table->family())) return false;
    1996           0 :     return route_aggregator(table->family())->IsContributingRoute(route);
    1997             : }
    1998             : 
    1999           0 : int RoutingInstance::GetOriginVnForAggregateRoute(Address::Family fmly) const {
    2000             :     SCAddress sc_addr;
    2001             :     SCAddress::Family sc_family =
    2002           0 :          sc_addr.AddressFamilyToSCFamily(fmly);
    2003             :     const ServiceChainConfig *sc_config =
    2004           0 :         config_ ? config_->service_chain_info(sc_family) : NULL;
    2005           0 :     if (sc_config && !sc_config->routing_instance.empty()) {
    2006             :         RoutingInstance *dest =
    2007           0 :             mgr_->GetRoutingInstanceLocked(sc_config->routing_instance);
    2008           0 :         if (dest) return dest->virtual_network_index();
    2009             :     }
    2010           0 :     return virtual_network_index_;
    2011             : }
    2012             : 
    2013           0 : size_t RoutingInstance::peer_manager_size() const {
    2014           0 :     return (peer_manager_ ? peer_manager_->size() : 0);
    2015             : }
    2016             : 
    2017          82 : PeerManager *RoutingInstance::LocatePeerManager() {
    2018          82 :     if (!peer_manager_)
    2019          20 :         peer_manager_.reset(BgpStaticObjectFactory::Create<PeerManager>(this));
    2020          82 :     return peer_manager_.get();
    2021             : }
    2022             : 
    2023             : // Get primary routing instance name from service RI names which works for both
    2024             : // in-network and transparent service chains. Use name based lookup to identify
    2025             : // the primary RI of service instance.
    2026             : // Service RI Name Format: <domain>:<project>:<VN>:<ServiceRI>
    2027             : // Primaru RI Name Format: <domain>:<project>:<VN>:<VN>
    2028           0 : string RoutingInstanceMgr::GetPrimaryRoutingInstanceName(const string &name) {
    2029           0 :     string n = name;
    2030           0 :     vector<string> tokens;
    2031           0 :     boost::split(tokens, n, boost::is_any_of(":"));
    2032           0 :     if (tokens.size() < 3)
    2033           0 :         return "";
    2034           0 :     ostringstream os;
    2035           0 :     os << tokens[0] << ":" << tokens[1] << ":" << tokens[2] << ":" << tokens[2];
    2036           0 :     return os.str();
    2037           0 : }

Generated by: LCOV version 1.14