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: 746 1224 60.9 %
Date: 2026-11-23 02:04:52 Functions: 93 129 72.1 %
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          68 :     explicit DeleteActor(RoutingInstanceMgr *manager)
      48          68 :         : LifetimeActor(manager->server_->lifetime_manager()),
      49          68 :           manager_(manager) {
      50          68 :     }
      51          68 :     virtual bool MayDelete() const {
      52          68 :         return manager_->MayDelete();
      53             :     }
      54          68 :     virtual void Shutdown() {
      55          68 :         manager_->Shutdown();
      56          68 :     }
      57          68 :     virtual void Destroy() {
      58          68 :         manager_->server_delete_ref_.Reset(NULL);
      59          68 :     }
      60             : 
      61             : private:
      62             :     RoutingInstanceMgr *manager_;
      63             : };
      64             : 
      65          68 : RoutingInstanceMgr::RoutingInstanceMgr(BgpServer *server) :
      66          68 :         server_(server),
      67         136 :         instance_config_lists_(
      68          68 :             TaskScheduler::GetInstance()->HardwareThreadCount()),
      69          68 :         default_rtinstance_(NULL),
      70          68 :         deleted_count_(0),
      71          68 :         asn_listener_id_(server->RegisterASNUpdateCallback(
      72             :             boost::bind(&RoutingInstanceMgr::ASNUpdateCallback, this, _1, _2))),
      73          68 :         identifier_listener_id_(server->RegisterIdentifierUpdateCallback(
      74             :             boost::bind(&RoutingInstanceMgr::IdentifierUpdateCallback,
      75             :                 this, _1))),
      76          68 :         dormant_trace_buf_size_(
      77          68 :                 GetEnvRoutingInstanceDormantTraceBufferCapacity()),
      78          68 :         trace_buf_threshold_(
      79          68 :                 GetEnvRoutingInstanceDormantTraceBufferThreshold()),
      80          68 :         deleter_(new DeleteActor(this)),
      81         204 :         server_delete_ref_(this, server->deleter()) {
      82          68 :     int task_id = TaskScheduler::GetInstance()->GetTaskId("bgp::ConfigHelper");
      83          68 :     int hw_thread_count = TaskScheduler::GetInstance()->HardwareThreadCount();
      84         340 :     for (int idx = 0; idx < hw_thread_count; ++idx) {
      85         544 :         instance_config_triggers_.push_back(new TaskTrigger(boost::bind(
      86             :             &RoutingInstanceMgr::ProcessInstanceConfigList, this, idx),
      87         272 :             task_id, idx));
      88             :     }
      89         136 :     neighbor_config_trigger_.reset(new TaskTrigger(
      90             :         boost::bind(&RoutingInstanceMgr::ProcessNeighborConfigList, this),
      91         136 :         TaskScheduler::GetInstance()->GetTaskId("bgp::Config"), 0));
      92          68 : }
      93             : 
      94         136 : RoutingInstanceMgr::~RoutingInstanceMgr() {
      95          68 :     assert(mvpn_project_managers_.empty());
      96          68 :     assert(virtual_networks_.empty());
      97          68 :     assert(deleted_count_ == 0);
      98          68 :     server_->UnregisterASNUpdateCallback(asn_listener_id_);
      99          68 :     server_->UnregisterIdentifierUpdateCallback(identifier_listener_id_);
     100          68 :     STLDeleteValues(&instance_config_triggers_);
     101         136 : }
     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          68 : void RoutingInstanceMgr::ManagedDelete() {
     115          68 :     deleter_->Delete();
     116          68 : }
     117             : 
     118          68 : void RoutingInstanceMgr::Shutdown() {
     119         170 :     for (RoutingInstanceIterator it = begin(); it != end(); ++it) {
     120         102 :         InstanceTargetRemove(it->second);
     121         102 :         InstanceVnIndexRemove(it->second);
     122             :     }
     123          68 : }
     124             : 
     125          68 : bool RoutingInstanceMgr::MayDelete() const {
     126          68 :     if (!neighbor_config_list_.empty())
     127           0 :         return false;
     128         340 :     for (size_t idx = 0; idx < instance_config_lists_.size(); ++idx) {
     129         272 :         if (!instance_config_lists_[idx].empty())
     130           0 :             return false;
     131             :     }
     132          68 :     return true;
     133             : }
     134             : 
     135         238 : LifetimeActor *RoutingInstanceMgr::deleter() {
     136         238 :     return deleter_.get();
     137             : }
     138             : 
     139         136 : bool RoutingInstanceMgr::deleted() {
     140         136 :     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         254 : void RoutingInstanceMgr::InstanceTargetAdd(RoutingInstance *rti) {
     152         254 :     std::scoped_lock lock(mutex_);
     153         254 :     for (RoutingInstance::RouteTargetList::const_iterator it =
     154         542 :          rti->GetExportList().begin(); it != rti->GetExportList().end(); ++it) {
     155          34 :         if (rti->GetImportList().find(*it) == rti->GetImportList().end())
     156           0 :             continue;
     157          34 :         target_map_.insert(make_pair(*it, rti));
     158             :     }
     159         254 : }
     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         254 : void RoutingInstanceMgr::InstanceTargetRemove(const RoutingInstance *rti) {
     171         254 :     std::scoped_lock lock(mutex_);
     172         254 :     for (RoutingInstance::RouteTargetList::const_iterator it =
     173         542 :          rti->GetExportList().begin(); it != rti->GetExportList().end(); ++it) {
     174          34 :         if (rti->GetImportList().find(*it) == rti->GetImportList().end())
     175           0 :             continue;
     176          34 :         for (InstanceTargetMap::iterator loc = target_map_.find(*it);
     177          34 :              loc != target_map_.end() && loc->first == *it; ++loc) {
     178          34 :             if (loc->second == rti) {
     179          34 :                 target_map_.erase(loc);
     180          34 :                 break;
     181             :             }
     182             :         }
     183             :     }
     184         254 : }
     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         254 : void RoutingInstanceMgr::InstanceVnIndexAdd(RoutingInstance *rti) {
     202         254 :     std::scoped_lock lock(mutex_);
     203         254 :     if (rti->virtual_network_index())
     204           0 :         vn_index_map_.insert(make_pair(rti->virtual_network_index(), rti));
     205         254 : }
     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         254 : void RoutingInstanceMgr::InstanceVnIndexRemove(const RoutingInstance *rti) {
     213         254 :     std::scoped_lock lock(mutex_);
     214         254 :     if (!rti->virtual_network_index())
     215         254 :         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         254 : }
     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        2270 : int RoutingInstanceMgr::GetVnIndexByRouteTarget(
     255             :         const RouteTarget &rtarget) const {
     256        2270 :     int vn_index = 0;
     257        2270 :     for (InstanceTargetMap::const_iterator loc = target_map_.find(rtarget);
     258        2269 :          loc != target_map_.end() && loc->first == rtarget; ++loc) {
     259           0 :         int ri_vn_index = loc->second->virtual_network_index();
     260           0 :         if (vn_index && ri_vn_index && ri_vn_index != vn_index)
     261           0 :             return -1;
     262           0 :         vn_index = ri_vn_index;
     263             :     }
     264             : 
     265        2269 :     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        2272 : int RoutingInstanceMgr::GetVnIndexByExtCommunity(
     276             :         const ExtCommunity *ext_community) const {
     277        2272 :     int vn_index = 0;
     278       21878 :     BOOST_FOREACH(const ExtCommunity::ExtCommunityValue &comm,
     279             :                   ext_community->communities()) {
     280        9802 :         if (!ExtCommunity::is_route_target(comm))
     281        7536 :             continue;
     282             : 
     283        2266 :         RouteTarget rtarget(comm);
     284        2270 :         int rtgt_vn_index = GetVnIndexByRouteTarget(rtarget);
     285        2269 :         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        2269 :         } else if (rtgt_vn_index) {
     290           0 :             vn_index = rtgt_vn_index;
     291             :         }
     292             :     }
     293             : 
     294        2271 :     return vn_index;
     295             : }
     296             : 
     297             : int
     298         323 : RoutingInstanceMgr::RegisterInstanceOpCallback(RoutingInstanceCb callback) {
     299         323 :     std::scoped_lock lock(mutex_);
     300         323 :     size_t i = bmap_.find_first();
     301         323 :     if (i == bmap_.npos) {
     302         323 :         i = callbacks_.size();
     303         323 :         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         323 :     return i;
     312         323 : }
     313             : 
     314         323 : void RoutingInstanceMgr::UnregisterInstanceOpCallback(int listener) {
     315         323 :     std::scoped_lock lock(mutex_);
     316         323 :     callbacks_[listener] = NULL;
     317         323 :     if ((size_t) listener == callbacks_.size() - 1) {
     318         415 :         while (!callbacks_.empty() && callbacks_.back() == NULL) {
     319         323 :             callbacks_.pop_back();
     320             :         }
     321          92 :         if (bmap_.size() > callbacks_.size()) {
     322          78 :             bmap_.resize(callbacks_.size());
     323             :         }
     324             :     } else {
     325         231 :         if ((size_t) listener >= bmap_.size()) {
     326         231 :             bmap_.resize(listener + 1);
     327             :         }
     328         231 :         bmap_.set(listener);
     329             :     }
     330         323 : }
     331             : 
     332         356 : void RoutingInstanceMgr::NotifyInstanceOp(string name, Operation op) {
     333         356 :     std::scoped_lock lock(mutex_);
     334         356 :     for (InstanceOpListenersList::iterator iter = callbacks_.begin();
     335        1831 :          iter != callbacks_.end(); ++iter) {
     336        1475 :         if (*iter != NULL) {
     337        1271 :             RoutingInstanceCb cb = *iter;
     338        1271 :             (cb)(name, op);
     339        1271 :         }
     340             :     }
     341         356 : }
     342             : 
     343          17 : bool RoutingInstanceMgr::ProcessInstanceConfigList(int idx) {
     344          17 :     if (deleted()) {
     345           0 :         deleter()->RetryDelete();
     346             :     } else {
     347          51 :         BOOST_FOREACH(const string &name, instance_config_lists_[idx]) {
     348             :             const BgpInstanceConfig *config =
     349          17 :                 server()->config_manager()->FindInstance(name);
     350          17 :             if (!config)
     351           0 :                 continue;
     352          17 :             LocateRoutingInstance(config);
     353             :         }
     354             :     }
     355             : 
     356          17 :     instance_config_lists_[idx].clear();
     357          17 :     return true;
     358             : }
     359             : 
     360        2371 : RoutingInstance *RoutingInstanceMgr::GetDefaultRoutingInstance() {
     361        2371 :     return default_rtinstance_;
     362             : }
     363             : 
     364           0 : const RoutingInstance *RoutingInstanceMgr::GetDefaultRoutingInstance() const {
     365           0 :     return default_rtinstance_;
     366             : }
     367             : 
     368        6047 : RoutingInstance *RoutingInstanceMgr::GetRoutingInstance(const string &name) {
     369        6047 :     RoutingInstanceList::iterator iter = instances_.find(name);
     370        6047 :     if (iter != instances_.end())
     371        6013 :         return iter->second;
     372          34 :     return NULL;
     373             : }
     374             : 
     375         130 : const RoutingInstance *RoutingInstanceMgr::GetRoutingInstance(
     376             :     const string &name) const {
     377         130 :     RoutingInstanceList::const_iterator iter = instances_.find(name);
     378         130 :     if (iter != instances_.end())
     379         130 :         return iter->second;
     380           0 :     return NULL;
     381             : }
     382             : 
     383         237 : RoutingInstance *RoutingInstanceMgr::GetRoutingInstanceLocked(
     384             :     const string &name) {
     385         237 :     std::scoped_lock lock(mutex_);
     386         237 :     RoutingInstanceList::iterator iter = instances_.find(name);
     387         237 :     if (iter != instances_.end())
     388         152 :         return iter->second;
     389          85 :     return NULL;
     390         237 : }
     391             : 
     392         102 : void RoutingInstanceMgr::InsertRoutingInstance(RoutingInstance *rtinstance) {
     393         102 :     std::scoped_lock lock(mutex_);
     394         102 :     instances_.insert(make_pair(rtinstance->config()->name(),
     395             :                 rtinstance));
     396         102 : }
     397             : 
     398         237 : void RoutingInstanceMgr::LocateRoutingInstance(
     399             :     const BgpInstanceConfig *config) {
     400         237 :     RoutingInstance *rtinstance = GetRoutingInstanceLocked(config->name());
     401         237 :     if (rtinstance) {
     402         152 :         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         152 :             UpdateRoutingInstance(rtinstance, config);
     409             :         }
     410             :     } else {
     411          85 :         rtinstance = CreateRoutingInstance(config);
     412             :     }
     413         237 : }
     414             : 
     415         271 : void RoutingInstanceMgr::LocateRoutingInstance(const string &name) {
     416             :     static boost::hash<string> string_hash;
     417             : 
     418         271 :     if (name == BgpConfigManager::kMasterInstance) {
     419             :         const BgpInstanceConfig *config =
     420         220 :             server()->config_manager()->FindInstance(name);
     421         220 :         assert(config);
     422         220 :         LocateRoutingInstance(config);
     423             :     } else {
     424          51 :         size_t idx = string_hash(name) % instance_config_lists_.size();
     425          51 :         instance_config_lists_[idx].insert(name);
     426          51 :         instance_config_triggers_[idx]->Set();
     427             :     }
     428         271 : }
     429             : 
     430             : // Update VirtualNetwork to RoutingInstance name mapping.
     431         102 : bool RoutingInstanceMgr::CreateVirtualNetworkMapping(
     432             :         const string &virtual_network, const string &instance_name) {
     433         102 :     std::scoped_lock lock(mutex_);
     434             : 
     435         102 :     VirtualNetworksMap::iterator iter;
     436             :     bool inserted;
     437         204 :     tie(iter, inserted) = virtual_networks_.insert(make_pair(virtual_network,
     438         306 :                                                              set<string>()));
     439         102 :     assert(iter->second.insert(instance_name).second);
     440         102 :     return true;
     441         102 : }
     442             : 
     443         102 : bool RoutingInstanceMgr::DeleteVirtualNetworkMapping(
     444             :         const string &virtual_network, const string &instance_name) {
     445         102 :     std::scoped_lock lock(mutex_);
     446             : 
     447         102 :     VirtualNetworksMap::iterator iter = virtual_networks_.find(virtual_network);
     448         102 :     assert(iter != virtual_networks_.end());
     449             : 
     450             :     // Delete this instance from the set of virtual-network to instances map.
     451         102 :     assert(iter->second.erase(instance_name) == 1);
     452             : 
     453         204 :     RoutingInstanceStatsData instance_info;
     454         102 :     bool mapping_deleted = iter->second.empty();
     455             : 
     456             :     // Delete the mapping if the member set is empty.
     457         102 :     if (mapping_deleted) {
     458         102 :         virtual_networks_.erase(iter);
     459             : 
     460             :         // Delete the virtual-network specific UVE.
     461         102 :         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         102 :     instance_info.set_name(virtual_network);
     478         102 :     assert(!instance_info.get_name().empty());
     479         102 :     BGP_UVE_SEND(RoutingInstanceStats, instance_info);
     480             : 
     481         102 :     return mapping_deleted;
     482         102 : }
     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         102 : RoutingInstance *RoutingInstanceMgr::CreateRoutingInstance(
     566             :     const BgpInstanceConfig *config) {
     567         102 :     RoutingInstance *rtinstance = BgpStaticObjectFactory::Create<RoutingInstance>(
     568         102 :         config->name(), server_, this, config);
     569         102 :     uint32_t ri_index = config->index();
     570         102 :     if (config->name() == BgpConfigManager::kMasterInstance) {
     571          68 :         default_rtinstance_ = rtinstance;
     572          68 :         ri_index = 0;
     573             :     }
     574             : 
     575         102 :     rtinstance->ProcessConfig();
     576         102 :     InsertRoutingInstance(rtinstance);
     577         102 :     rtinstance->set_index(ri_index);
     578             : 
     579         102 :     InstanceTargetAdd(rtinstance);
     580         102 :     InstanceVnIndexAdd(rtinstance);
     581         102 :     rtinstance->InitAllRTargetRoutes(server_->local_autonomous_system());
     582             : 
     583             :     // Notify clients about routing instance create
     584         102 :     NotifyInstanceOp(config->name(), INSTANCE_ADD);
     585             : 
     586         102 :     vector<string> import_rt(config->import_list().begin(),
     587         204 :                                   config->import_list().end());
     588         102 :     vector<string> export_rt(config->export_list().begin(),
     589         204 :                                   config->export_list().end());
     590         102 :     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         102 :     CreateRoutingInstanceNeighbors(config);
     596             : 
     597             :     //  Update instance to virtual-network mapping structures.
     598         102 :     CreateVirtualNetworkMapping(rtinstance->GetVirtualNetworkName(),
     599             :                                 rtinstance->name());
     600             : 
     601             :     // Create MvpnManager for all children mvpn networks.
     602             :     MvpnTable *mvpn_table =
     603         102 :         dynamic_cast<MvpnTable *>(rtinstance->GetTable(Address::MVPN));
     604         102 :     mvpn_table->CreateMvpnManagers();
     605         102 :     return rtinstance;
     606         102 : }
     607             : 
     608         152 : void RoutingInstanceMgr::UpdateRoutingInstance(RoutingInstance *rtinstance,
     609             :     const BgpInstanceConfig *config) {
     610         152 :     bool old_always_subscribe = rtinstance->always_subscribe();
     611             : 
     612             :     // Note that InstanceTarget[Remove|Add] depend on the RouteTargetList in
     613             :     // the RoutingInstance.
     614         152 :     InstanceTargetRemove(rtinstance);
     615         152 :     InstanceVnIndexRemove(rtinstance);
     616         152 :     rtinstance->UpdateConfig(config);
     617         152 :     InstanceTargetAdd(rtinstance);
     618         152 :     InstanceVnIndexAdd(rtinstance);
     619             : 
     620         152 :     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         152 :     NotifyInstanceOp(config->name(), INSTANCE_UPDATE);
     627             : 
     628         152 :     vector<string> import_rt(config->import_list().begin(),
     629         304 :                                   config->import_list().end());
     630         152 :     vector<string> export_rt(config->export_list().begin(),
     631         304 :                                   config->export_list().end());
     632         152 :     RTINSTANCE_LOG(Update, rtinstance,
     633             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL, import_rt, export_rt,
     634             :         rtinstance->virtual_network_index());
     635         152 : }
     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         102 : void RoutingInstanceMgr::DestroyRoutingInstance(RoutingInstance *rtinstance) {
     683         102 :     CHECK_CONCURRENCY("bgp::Config");
     684             : 
     685         102 :     RTINSTANCE_LOG(Destroy, rtinstance,
     686             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL);
     687             : 
     688         102 :     DeleteVirtualNetworkMapping(rtinstance->GetVirtualNetworkName(),
     689             :                                 rtinstance->name());
     690             : 
     691             :     // instance should also be deleted here
     692         102 :     const string name = rtinstance->name();
     693         102 :     RoutingInstanceList::iterator loc = instances_.find(rtinstance->name());
     694         102 :     assert(loc != instances_.end());
     695         102 :     instances_.erase(loc);
     696         102 :     int index = rtinstance->index();
     697         102 :     delete rtinstance;
     698             :     // disable the TraceBuf for the deleted RoutingInstance
     699         102 :     DisableTraceBuffer(name);
     700             :     // index was allocated in Config Manager so needs to be freed
     701         102 :     if (index >= 0)
     702          85 :         server()->config_manager()->ResetRoutingInstanceIndexBit(index);
     703             : 
     704         102 :     if (deleted())
     705         102 :         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         102 : }
     719             : 
     720        2192 : SandeshTraceBufferPtr RoutingInstanceMgr::LocateTraceBuffer(
     721             :         const std::string &name) {
     722        2192 :     SandeshTraceBufferPtr trace_buf;
     723             : 
     724        2192 :     trace_buf = GetActiveTraceBuffer(name);
     725        2192 :     if (trace_buf == NULL) {
     726         102 :         trace_buf = GetTraceBuffer(name);
     727             :     }
     728             : 
     729        2192 :     return trace_buf;
     730           0 : }
     731             : 
     732         102 : SandeshTraceBufferPtr RoutingInstanceMgr::GetTraceBuffer(
     733             :         const std::string &name) {
     734         102 :     tbb::spin_rw_mutex::scoped_lock write_lock(rw_mutex_, true);
     735         102 :     SandeshTraceBufferPtr trace_buf;
     736         102 :     RoutingInstanceTraceBufferMap::iterator iter;
     737             : 
     738         102 :     iter = trace_buffer_active_.find(name);
     739         102 :     if (iter != trace_buffer_active_.end()) {
     740           0 :         return iter->second;
     741             :     }
     742             : 
     743         102 :     iter = trace_buffer_dormant_.find(name);
     744         102 :     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         204 :     trace_buf = SandeshTraceBufferCreate(
     756         306 :                                   name + RTINSTANCE_TRACE_BUF, 1000);
     757         102 :     trace_buffer_active_.insert(make_pair(name, trace_buf));
     758             : 
     759         102 :     return trace_buf;
     760         102 : }
     761             : 
     762         102 : void RoutingInstanceMgr::DisableTraceBuffer(const std::string &name) {
     763         102 :     tbb::spin_rw_mutex::scoped_lock write_lock(rw_mutex_, true);
     764         102 :     SandeshTraceBufferPtr trace_buf;
     765         102 :     SandeshTraceBufferPtr trace_buf_delete;
     766         102 :     RoutingInstanceTraceBufferMap::iterator iter;
     767         102 :     std::pair<RoutingInstanceTraceBufferMap::iterator, bool> ret;
     768         102 :     std::string ri_name;
     769             : 
     770             :     // Moving the trace buff from Active map to Dormant map
     771         102 :     iter = trace_buffer_active_.find(name);
     772         102 :     if (iter != trace_buffer_active_.end()) {
     773         102 :         trace_buf = iter->second;
     774         102 :         trace_buffer_active_.erase(iter);
     775         102 :         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         204 :     return;
     804         102 : }
     805             : 
     806             : SandeshTraceBufferPtr
     807        2192 : RoutingInstanceMgr::GetActiveTraceBuffer(const std::string &name) const {
     808        2192 :     tbb::spin_rw_mutex::scoped_lock read_lock(rw_mutex_, false);
     809             :     RoutingInstanceTraceBufferMap::const_iterator iter =
     810        2192 :                                          trace_buffer_active_.find(name);
     811             : 
     812        2192 :     if (iter != trace_buffer_active_.end()) {
     813        2090 :         return iter->second;
     814             :     } else {
     815         102 :         return SandeshTraceBufferPtr();
     816             :     }
     817        2192 : }
     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          68 : RoutingInstanceMgr::GetEnvRoutingInstanceDormantTraceBufferCapacity() const {
     851          68 :     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          68 :     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          68 :     return 0;
     859             : }
     860             : 
     861             : size_t
     862          68 : RoutingInstanceMgr::GetEnvRoutingInstanceDormantTraceBufferThreshold() const {
     863          68 :     char *buffer_threshold_str = getenv(
     864             :             "CONTRAIL_ROUTING_INSTANCE_DORMANT_TRACE_BUFFER_THRESHOLD");
     865          68 :     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          68 :     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         102 : void RoutingInstanceMgr::CreateRoutingInstanceNeighbors(
     883             :     const BgpInstanceConfig *config) {
     884         102 :     if (config->neighbor_list().empty())
     885          85 :         return;
     886          17 :     std::scoped_lock lock(mutex_);
     887          17 :     neighbor_config_list_.insert(config->name());
     888          17 :     neighbor_config_trigger_->Set();
     889          17 : }
     890             : 
     891          17 : bool RoutingInstanceMgr::ProcessNeighborConfigList() {
     892          17 :     if (deleted()) {
     893           0 :         deleter()->RetryDelete();
     894             :     } else {
     895          51 :         BOOST_FOREACH(const string &name, neighbor_config_list_) {
     896          17 :             RoutingInstance *rtinstance = GetRoutingInstance(name);
     897          17 :             if (!rtinstance || rtinstance->deleted())
     898           0 :                 continue;
     899          17 :             rtinstance->CreateNeighbors();
     900             :         }
     901             :     }
     902             : 
     903          17 :     neighbor_config_list_.clear();
     904          17 :     return true;
     905             : }
     906             : 
     907          84 : void RoutingInstanceMgr::ASNUpdateCallback(as_t old_asn, as_t old_local_asn) {
     908          84 :     if (server_->local_autonomous_system() == old_local_asn)
     909           0 :         return;
     910         168 :     for (RoutingInstanceIterator it = begin(); it != end(); ++it) {
     911          84 :         it->second->FlushAllRTargetRoutes(old_local_asn);
     912          84 :         it->second->InitAllRTargetRoutes(server_->local_autonomous_system());
     913             :     }
     914          84 :     RoutingInstance *master = GetDefaultRoutingInstance();
     915          84 :     const Ip4Address old_identifier(server()->bgp_identifier());
     916          84 :     master->DeleteMvpnRTargetRoute(old_local_asn, old_identifier);
     917          84 :     master->AddMvpnRTargetRoute(server_->local_autonomous_system());
     918             : }
     919             : 
     920          68 : void RoutingInstanceMgr::IdentifierUpdateCallback(Ip4Address old_identifier) {
     921         136 :     for (RoutingInstanceIterator it = begin(); it != end(); ++it) {
     922          68 :         it->second->ProcessIdentifierUpdate(server_->local_autonomous_system());
     923             :     }
     924          68 :     RoutingInstance *master = GetDefaultRoutingInstance();
     925          68 :     master->DeleteMvpnRTargetRoute(server_->local_autonomous_system(),
     926             :             old_identifier);
     927          68 :     master->AddMvpnRTargetRoute(server_->local_autonomous_system());
     928          68 : }
     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         102 :     DeleteActor(BgpServer *server, RoutingInstance *parent)
     969         102 :             : LifetimeActor(server ? server->lifetime_manager() : NULL),
     970         204 :                             parent_(parent) {
     971         102 :     }
     972         102 :     virtual bool MayDelete() const {
     973         102 :         return parent_->MayDelete();
     974             :     }
     975         102 :     virtual void Shutdown() {
     976         102 :         parent_->mgr_->increment_deleted_count();
     977         102 :         parent_->mgr_->NotifyInstanceOp(parent_->name(),
     978             :                                         RoutingInstanceMgr::INSTANCE_DELETE);
     979         102 :         parent_->Shutdown();
     980         102 :     }
     981         102 :     virtual void Destroy() {
     982         102 :         parent_->mgr_->decrement_deleted_count();
     983         102 :         parent_->mgr_->DestroyRoutingInstance(parent_);
     984         102 :     }
     985             : 
     986             : private:
     987             :     RoutingInstance *parent_;
     988             : };
     989             : 
     990         102 : RoutingInstance::RoutingInstance(string name, BgpServer *server,
     991             :                                  RoutingInstanceMgr *mgr,
     992         102 :                                  const BgpInstanceConfig *config)
     993         306 :     : name_(name), index_(-1), server_(server), mgr_(mgr), config_(config),
     994         204 :       is_master_(false), always_subscribe_(false), virtual_network_index_(0),
     995         102 :       virtual_network_allow_transit_(false),
     996         102 :       virtual_network_pbb_evpn_enable_(false),
     997         102 :       vxlan_id_(0),
     998         102 :       deleter_(new DeleteActor(server, this)),
     999         102 :       manager_delete_ref_(this, NULL),
    1000         204 :       mvpn_project_manager_network_(BgpConfigManager::kFabricInstance) {
    1001         102 :     if (mgr) {
    1002         102 :         std::scoped_lock lock(mgr->mutex());
    1003         102 :         manager_delete_ref_.Reset(mgr->deleter());
    1004         102 :     }
    1005         102 : }
    1006             : 
    1007         204 : RoutingInstance::~RoutingInstance() {
    1008         204 : }
    1009             : 
    1010          17 : void RoutingInstance::CreateNeighbors() {
    1011          17 :     CHECK_CONCURRENCY("bgp::Config");
    1012             : 
    1013          17 :     if (config_->neighbor_list().empty())
    1014           0 :         return;
    1015          17 :     PeerManager *peer_manager = LocatePeerManager();
    1016          85 :     BOOST_FOREACH(const string &name, config_->neighbor_list()) {
    1017          34 :         if (peer_manager->PeerLookup(name))
    1018           0 :             continue;
    1019          34 :         peer_manager->PeerResurrect(name);
    1020             :     }
    1021             : }
    1022             : 
    1023         102 : void RoutingInstance::ProcessRoutingPolicyConfig() {
    1024         102 :     RoutingPolicyMgr *policy_mgr = server()->routing_policy_mgr();
    1025         102 :     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         102 : }
    1035             : 
    1036        2192 : SandeshTraceBufferPtr RoutingInstance::trace_buffer() const {
    1037        2192 :     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           0 : void RoutingInstance::UpdateRoutingPolicyConfig() {
    1050           0 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1051           0 :     RoutingPolicyMgr *policy_mgr = server()->routing_policy_mgr();
    1052           0 :     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           0 : }
    1058             : 
    1059         204 : void RoutingInstance::ProcessServiceChainConfig() {
    1060         204 :     if (is_master_)
    1061         136 :         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          68 :         (SCAddress::INET) (SCAddress::INET6)
    1076          68 :         (SCAddress::EVPN) (SCAddress::EVPN6);
    1077             : 
    1078         612 :     BOOST_FOREACH(SCAddress::Family family, families) {
    1079             :         const ServiceChainConfig *sc_config =
    1080         272 :             config_ ? config_->service_chain_info(family) : NULL;
    1081         272 :         IServiceChainMgr *manager = server_->service_chain_mgr(family);
    1082         272 :         if (sc_config && !sc_config->routing_instance.empty()) {
    1083           0 :             manager->LocateServiceChain(this, *sc_config);
    1084             :         } else {
    1085         272 :             manager->StopServiceChain(this);
    1086             :         }
    1087             :     }
    1088          68 : }
    1089             : 
    1090         102 : void RoutingInstance::ProcessStaticRouteConfig() {
    1091         102 :     if (is_master_)
    1092          68 :         return;
    1093             : 
    1094          34 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1095         170 :     BOOST_FOREACH(Address::Family family, families) {
    1096          68 :         IStaticRouteMgr *manager = static_route_mgr(family);
    1097          68 :         if (!manager && !config_->static_routes(family).empty())
    1098           0 :             manager = LocateStaticRouteMgr(family);
    1099          68 :         if (manager)
    1100           0 :             manager->ProcessStaticRouteConfig();
    1101             :     }
    1102          34 : }
    1103             : 
    1104           0 : void RoutingInstance::UpdateStaticRouteConfig() {
    1105           0 :     if (is_master_)
    1106           0 :         return;
    1107             : 
    1108           0 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1109           0 :     BOOST_FOREACH(Address::Family family, families) {
    1110           0 :         IStaticRouteMgr *manager = static_route_mgr(family);
    1111           0 :         if (!manager && !config_->static_routes(family).empty())
    1112           0 :             manager = LocateStaticRouteMgr(family);
    1113           0 :         if (manager)
    1114           0 :             manager->UpdateStaticRouteConfig();
    1115             :     }
    1116           0 : }
    1117             : 
    1118         102 : void RoutingInstance::FlushStaticRouteConfig() {
    1119         102 :     if (is_master_)
    1120          68 :         return;
    1121             : 
    1122          34 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1123         170 :     BOOST_FOREACH(Address::Family family, families) {
    1124          68 :         IStaticRouteMgr *manager = static_route_mgr(family);
    1125          68 :         if (manager)
    1126           0 :             manager->FlushStaticRouteConfig();
    1127             :     }
    1128          34 : }
    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         102 : void RoutingInstance::ProcessRouteAggregationConfig() {
    1143         102 :     if (is_master_)
    1144          68 :         return;
    1145             : 
    1146          34 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1147         170 :     BOOST_FOREACH(Address::Family family, families) {
    1148          68 :         IRouteAggregator *aggregator = route_aggregator(family);
    1149          68 :         if (!aggregator && !config_->aggregate_routes(family).empty())
    1150           0 :             aggregator = LocateRouteAggregator(family);
    1151          68 :         if (aggregator)
    1152           0 :             aggregator->ProcessAggregateRouteConfig();
    1153             :     }
    1154          34 : }
    1155             : 
    1156           0 : void RoutingInstance::UpdateRouteAggregationConfig() {
    1157           0 :     if (is_master_)
    1158           0 :         return;
    1159             : 
    1160           0 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1161           0 :     BOOST_FOREACH(Address::Family family, families) {
    1162           0 :         IRouteAggregator *aggregator = route_aggregator(family);
    1163           0 :         if (!aggregator && !config_->aggregate_routes(family).empty())
    1164           0 :             aggregator = LocateRouteAggregator(family);
    1165           0 :         if (aggregator)
    1166           0 :             aggregator->UpdateAggregateRouteConfig();
    1167             :     }
    1168           0 : }
    1169             : 
    1170         102 : void RoutingInstance::FlushRouteAggregationConfig() {
    1171         102 :     if (is_master_)
    1172          68 :         return;
    1173             : 
    1174          34 :     vector<Address::Family> families = list_of(Address::INET)(Address::INET6);
    1175         170 :     BOOST_FOREACH(Address::Family family, families) {
    1176          68 :         IRouteAggregator *aggregator = route_aggregator(family);
    1177          68 :         if (aggregator)
    1178           0 :             aggregator->FlushAggregateRouteConfig();
    1179             :     }
    1180          34 : }
    1181             : 
    1182         220 : void RoutingInstance::DeleteMvpnRTargetRoute(as_t asn, Ip4Address old_ip) {
    1183         220 :     if (asn == 0)
    1184         136 :         return;
    1185         168 :     string id_str = "target:" + old_ip.to_string() + ":0";
    1186          84 :     RouteTarget rtarget = RouteTarget::FromString(id_str);
    1187          84 :     DeleteRTargetRoute(asn, rtarget);
    1188          84 : }
    1189             : 
    1190         152 : void RoutingInstance::AddMvpnRTargetRoute(as_t asn) {
    1191         152 :     if (asn == 0)
    1192          68 :         return;
    1193          84 :     const Ip4Address server_ip(server()->bgp_identifier());
    1194         168 :     string id_str = "target:" + server_ip.to_string() + ":0";
    1195          84 :     RouteTarget rtarget = RouteTarget::FromString(id_str);
    1196          84 :     AddRTargetRoute(asn, rtarget);
    1197          84 : }
    1198             : 
    1199         102 : void RoutingInstance::ProcessConfig() {
    1200         102 :     RoutingInstanceInfo info = GetDataCollection("");
    1201             : 
    1202             :     // Initialize virtual network info.
    1203         102 :     virtual_network_ = config_->virtual_network();
    1204         102 :     virtual_network_index_ = config_->virtual_network_index();
    1205         102 :     virtual_network_allow_transit_ = config_->virtual_network_allow_transit();
    1206         102 :     virtual_network_pbb_evpn_enable_ =
    1207         102 :         config_->virtual_network_pbb_evpn_enable();
    1208         102 :     vxlan_id_ = config_->vxlan_id();
    1209         102 :     routing_instance_vxlan_ = config_->routing_instance_vxlan();
    1210             : 
    1211             :     // Always subscribe (using RTF) for RTs of PNF service chain instances.
    1212         102 :     always_subscribe_ = config_->has_pnf();
    1213             : 
    1214         102 :     vector<string> import_rt, export_rt;
    1215         238 :     BOOST_FOREACH(string irt, config_->import_list()) {
    1216          68 :         error_code error;
    1217          68 :         RouteTarget rt = RouteTarget::FromString(irt, &error);
    1218          68 :         if (!error) {
    1219          68 :             import_.insert(rt);
    1220          68 :             import_rt.push_back(irt);
    1221             :         }
    1222          68 :     }
    1223         170 :     BOOST_FOREACH(string ert, config_->export_list()) {
    1224          34 :         error_code error;
    1225          34 :         RouteTarget rt = RouteTarget::FromString(ert, &error);
    1226          34 :         if (!error) {
    1227          34 :             export_.insert(rt);
    1228          34 :             export_rt.push_back(ert);
    1229             :         }
    1230          34 :     }
    1231         102 :     RTINSTANCE_LOG(Update, this,
    1232             :                 SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL,
    1233             :                 import_rt, export_rt, this->virtual_network_index());
    1234             : 
    1235         102 :     if (import_rt.size())
    1236          34 :         info.set_add_import_rt(import_rt);
    1237         102 :     if (export_rt.size())
    1238          34 :         info.set_add_export_rt(export_rt);
    1239         102 :     if (import_rt.size() || export_rt.size())
    1240          34 :         ROUTING_INSTANCE_COLLECTOR_INFO(info);
    1241             : 
    1242             :     // Create BGP Table
    1243         102 :     if (name_ == BgpConfigManager::kMasterInstance) {
    1244          68 :         assert(mgr_->count() == 0);
    1245          68 :         is_master_ = true;
    1246             : 
    1247          68 :         LocatePeerManager();
    1248          68 :         VpnTableCreate(Address::INETVPN);
    1249          68 :         VpnTableCreate(Address::INET6VPN);
    1250          68 :         VpnTableCreate(Address::ERMVPN);
    1251          68 :         VpnTableCreate(Address::MVPN);
    1252          68 :         VpnTableCreate(Address::EVPN);
    1253          68 :         RTargetTableCreate();
    1254             : 
    1255             :         BgpTable *table_inet = static_cast<BgpTable *>(
    1256          68 :             server_->database()->CreateTable("inet.0"));
    1257          68 :         assert(table_inet);
    1258          68 :         AddTable(table_inet);
    1259             : 
    1260             :         BgpTable *table_inetmpls = static_cast<BgpTable *>(
    1261          68 :             server_->database()->CreateTable("inet.3"));
    1262          68 :         assert(table_inetmpls);
    1263          68 :         AddTable(table_inetmpls);
    1264             : 
    1265             :         BgpTable *table_inet6 = static_cast<BgpTable *>(
    1266          68 :             server_->database()->CreateTable("inet6.0"));
    1267          68 :         assert(table_inet6);
    1268          68 :         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          34 :         BgpTable *inet_table = VrfTableCreate(Address::INET, Address::INETVPN);
    1274          34 :         inet_table->LocatePathResolver();
    1275             : 
    1276             :         BgpTable *inet6_table =
    1277          34 :             VrfTableCreate(Address::INET6, Address::INET6VPN);
    1278          34 :         inet6_table->LocatePathResolver();
    1279             : 
    1280          34 :         VrfTableCreate(Address::ERMVPN, Address::ERMVPN);
    1281             : 
    1282          34 :         BgpTable *evpn_table = VrfTableCreate(Address::EVPN, Address::EVPN);
    1283          34 :         evpn_table->LocatePathResolver();
    1284             : 
    1285          34 :         BgpTable *table = VrfTableCreate(Address::MVPN, Address::MVPN);
    1286             : 
    1287             :         // Create path-resolver in mvpn table.
    1288          34 :         table->LocatePathResolver();
    1289             :     }
    1290             : 
    1291         102 :     ProcessServiceChainConfig();
    1292         102 :     ProcessStaticRouteConfig();
    1293         102 :     ProcessRouteAggregationConfig();
    1294         102 :     ProcessRoutingPolicyConfig();
    1295         102 : }
    1296             : 
    1297         152 : void RoutingInstance::UpdateConfig(const BgpInstanceConfig *cfg) {
    1298         152 :     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         152 :     config_ = cfg;
    1303             : 
    1304             :     // Always subscribe (using RTF) for RTs of PNF service chain instances.
    1305         152 :     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         152 :     bool notify_routes = false;
    1310         152 :     if (virtual_network_allow_transit_ != cfg->virtual_network_allow_transit())
    1311           0 :         notify_routes = true;
    1312         152 :     if (virtual_network_pbb_evpn_enable_ !=
    1313         152 :         cfg->virtual_network_pbb_evpn_enable())
    1314           0 :         notify_routes = true;
    1315         152 :     if (virtual_network_ != cfg->virtual_network())
    1316           0 :         notify_routes = true;
    1317         152 :     if (virtual_network_index_ != cfg->virtual_network_index())
    1318           0 :         notify_routes = true;
    1319             : 
    1320             :     // Trigger notification of all routes in each table.
    1321         152 :     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         152 :     if (virtual_network_index_ != cfg->virtual_network_index())
    1330           0 :         UpdateAllStaticRoutes();
    1331             : 
    1332         152 :     string prev_vn_name = GetVirtualNetworkName();
    1333             : 
    1334             :     // Update virtual network info.
    1335         152 :     virtual_network_ = cfg->virtual_network();
    1336             : 
    1337             :     // Recreate instance stats' UVE, if its key: virtual_network is modified.
    1338         152 :     if (prev_vn_name != GetVirtualNetworkName()) {
    1339           0 :         mgr_->DeleteVirtualNetworkMapping(prev_vn_name, name_);
    1340           0 :         mgr_->CreateVirtualNetworkMapping(GetVirtualNetworkName(), name_);
    1341             :     }
    1342             : 
    1343         152 :     virtual_network_index_ = cfg->virtual_network_index();
    1344         152 :     virtual_network_allow_transit_ = cfg->virtual_network_allow_transit();
    1345         152 :     virtual_network_pbb_evpn_enable_ = cfg->virtual_network_pbb_evpn_enable();
    1346         152 :     vxlan_id_ = cfg->vxlan_id();
    1347         152 :     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         152 :     if (IsMasterRoutingInstance())
    1352         152 :         return;
    1353             : 
    1354           0 :     RouteTargetList future_import;
    1355           0 :     vector<string> add_import_rt, remove_import_rt;
    1356           0 :     BOOST_FOREACH(const string &rtarget_str, cfg->import_list()) {
    1357           0 :         error_code error;
    1358           0 :         RouteTarget rt = RouteTarget::FromString(rtarget_str, &error);
    1359           0 :         if (!error)
    1360           0 :             future_import.insert(rt);
    1361             :     }
    1362           0 :     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           0 :     RouteTargetList future_export;
    1369           0 :     vector<string> add_export_rt, remove_export_rt;
    1370           0 :     BOOST_FOREACH(const string &rtarget_str, cfg->export_list()) {
    1371           0 :         error_code error;
    1372           0 :         RouteTarget rt = RouteTarget::FromString(rtarget_str, &error);
    1373           0 :         if (!error)
    1374           0 :             future_export.insert(rt);
    1375             :     }
    1376           0 :     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           0 :     RoutingInstanceInfo info = GetDataCollection("");
    1383           0 :     if (add_import_rt.size())
    1384           0 :         info.set_add_import_rt(add_import_rt);
    1385           0 :     if (remove_import_rt.size())
    1386           0 :         info.set_remove_import_rt(remove_import_rt);
    1387           0 :     if (add_export_rt.size())
    1388           0 :         info.set_add_export_rt(add_export_rt);
    1389           0 :     if (remove_export_rt.size())
    1390           0 :         info.set_remove_export_rt(remove_export_rt);
    1391           0 :     if (add_import_rt.size() || remove_import_rt.size() ||
    1392           0 :         add_export_rt.size() || remove_export_rt.size())
    1393           0 :         ROUTING_INSTANCE_COLLECTOR_INFO(info);
    1394             : 
    1395           0 :     ProcessServiceChainConfig();
    1396           0 :     UpdateStaticRouteConfig();
    1397           0 :     UpdateRouteAggregationConfig();
    1398           0 :     UpdateRoutingPolicyConfig();
    1399         152 : }
    1400             : 
    1401         102 : void RoutingInstance::ClearConfig() {
    1402         102 :     CHECK_CONCURRENCY("bgp::Config");
    1403         102 :     config_ = NULL;
    1404         102 : }
    1405             : 
    1406         102 : void RoutingInstance::ManagedDelete() {
    1407             :     // RoutingInstanceMgr logs the delete for non-master instances.
    1408         102 :     if (IsMasterRoutingInstance()) {
    1409          68 :         RTINSTANCE_LOG(Delete, this,
    1410             :             SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL);
    1411             :     }
    1412         102 :     deleter_->Delete();
    1413         102 : }
    1414             : 
    1415         102 : void RoutingInstance::Shutdown() {
    1416         102 :     CHECK_CONCURRENCY("bgp::Config");
    1417             : 
    1418         102 :     RTINSTANCE_LOG(Shutdown, this,
    1419             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL);
    1420             : 
    1421         102 :     ClearConfig();
    1422         102 :     FlushAllRTargetRoutes(server_->local_autonomous_system());
    1423         102 :     if (is_master_) {
    1424          68 :         const Ip4Address old_identifier(server()->bgp_identifier());
    1425          68 :         DeleteMvpnRTargetRoute(server_->local_autonomous_system(),
    1426             :                 old_identifier);
    1427             :     }
    1428         102 :     ClearRouteTarget();
    1429             : 
    1430         102 :     ProcessServiceChainConfig();
    1431         102 :     FlushStaticRouteConfig();
    1432         102 :     FlushRouteAggregationConfig();
    1433         102 : }
    1434             : 
    1435         102 : bool RoutingInstance::MayDelete() const {
    1436         102 :     return true;
    1437             : }
    1438             : 
    1439         952 : LifetimeActor *RoutingInstance::deleter() {
    1440         952 :     return deleter_.get();
    1441             : }
    1442             : 
    1443        3355 : const LifetimeActor *RoutingInstance::deleter() const {
    1444        3355 :     return deleter_.get();
    1445             : }
    1446             : 
    1447        3355 : bool RoutingInstance::deleted() const {
    1448        3355 :     return deleter()->IsDeleted();
    1449             : }
    1450             : 
    1451       10655 : const string RoutingInstance::GetVirtualNetworkName() const {
    1452       10655 :     if (!virtual_network_.empty())
    1453           0 :         return virtual_network_;
    1454       10655 :     size_t pos = name_.rfind(':');
    1455       10655 :     if (pos == string::npos) {
    1456        5559 :         return name_;
    1457             :     } else {
    1458        5096 :         return name_.substr(0, pos);
    1459             :     }
    1460             : }
    1461             : 
    1462        9487 : int RoutingInstance::virtual_network_index() const {
    1463        9487 :     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         170 : void RoutingInstance::ClearFamilyRouteTarget(Address::Family vrf_family,
    1479             :                                              Address::Family vpn_family) {
    1480         170 :     BgpTable *table = GetTable(vrf_family);
    1481         170 :     if (table) {
    1482         170 :         RoutePathReplicator *replicator = server_->replicator(vpn_family);
    1483         850 :         BOOST_FOREACH(RouteTarget rt, import_) {
    1484         340 :             replicator->Leave(table, rt, true);
    1485             :         }
    1486         510 :         BOOST_FOREACH(RouteTarget rt, export_) {
    1487         170 :             replicator->Leave(table, rt, false);
    1488             :         }
    1489             :     }
    1490         170 : }
    1491             : 
    1492          84 : void RoutingInstance::AddRTargetRoute(uint32_t asn,
    1493             :     const RouteTarget &rtarget) {
    1494          84 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1495             : 
    1496          84 :     RTargetPrefix prefix(asn, rtarget);
    1497          84 :     RTargetRoute rt_key(prefix);
    1498             : 
    1499          84 :     RoutingInstance *master = mgr_->GetDefaultRoutingInstance();
    1500          84 :     BgpTable *table = master->GetTable(Address::RTARGET);
    1501             :     DBTablePartition *tbl_partition =
    1502          84 :         static_cast<DBTablePartition *>(table->GetTablePartition(0));
    1503             : 
    1504          84 :     std::scoped_lock lock(mgr_->mutex());
    1505             :     RTargetRoute *route =
    1506          84 :         static_cast<RTargetRoute *>(tbl_partition->Find(&rt_key));
    1507          84 :     if (!route) {
    1508          84 :         route = new RTargetRoute(prefix);
    1509          84 :         tbl_partition->Add(route);
    1510             :     } else {
    1511           0 :         route->ClearDelete();
    1512             :     }
    1513             : 
    1514          84 :     if (route->FindPath(BgpPath::Local, index_))
    1515           0 :         return;
    1516             : 
    1517          84 :     BgpAttrSpec attr_spec;
    1518          84 :     BgpAttrNextHop nexthop(server_->bgp_identifier());
    1519          84 :     attr_spec.push_back(&nexthop);
    1520          84 :     BgpAttrOrigin origin(BgpAttrOrigin::IGP);
    1521          84 :     attr_spec.push_back(&origin);
    1522          84 :     BgpAttrPtr attr = server_->attr_db()->Locate(attr_spec);
    1523             : 
    1524          84 :     BgpPath *path = new BgpPath(index_, BgpPath::Local, attr);
    1525          84 :     route->InsertPath(path);
    1526          84 :     tbl_partition->Notify(route);
    1527          84 :     BGP_LOG_ROUTE(table, static_cast<IPeer *>(NULL),
    1528             :         route, "Insert Local path with path id " << index_);
    1529          84 : }
    1530             : 
    1531         152 : void RoutingInstance::DeleteRTargetRoute(as_t asn,
    1532             :     const RouteTarget &rtarget) {
    1533         152 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1534             : 
    1535         152 :     if (asn == 0)
    1536          68 :         return;
    1537             : 
    1538         152 :     RTargetPrefix prefix(asn, rtarget);
    1539         152 :     RTargetRoute rt_key(prefix);
    1540             : 
    1541         152 :     RoutingInstance *master = mgr_->GetDefaultRoutingInstance();
    1542         152 :     BgpTable *table = master->GetTable(Address::RTARGET);
    1543             :     DBTablePartition *tbl_partition =
    1544         152 :         static_cast<DBTablePartition *>(table->GetTablePartition(0));
    1545             : 
    1546         152 :     std::scoped_lock lock(mgr_->mutex());
    1547             :     RTargetRoute *route =
    1548         152 :         static_cast<RTargetRoute *>(tbl_partition->Find(&rt_key));
    1549         152 :     if (!route || !route->RemovePath(BgpPath::Local, index_))
    1550          68 :         return;
    1551             : 
    1552          84 :     BGP_LOG_ROUTE(table, static_cast<IPeer *>(NULL),
    1553             :         route, "Delete Local path with path id " << index_);
    1554          84 :     if (!route->HasPaths()) {
    1555          84 :         tbl_partition->Delete(route);
    1556             :     } else {
    1557           0 :         tbl_partition->Notify(route);
    1558             :     }
    1559         220 : }
    1560             : 
    1561         254 : void RoutingInstance::InitAllRTargetRoutes(as_t asn) {
    1562         254 :     if (is_master_)
    1563         220 :         return;
    1564             : 
    1565          34 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1566         170 :     BOOST_FOREACH(RouteTarget rtarget, import_) {
    1567          68 :         if (asn != 0 && always_subscribe_)
    1568           0 :             AddRTargetRoute(asn, rtarget);
    1569             :     }
    1570             : }
    1571             : 
    1572         254 : void RoutingInstance::FlushAllRTargetRoutes(as_t asn) {
    1573         254 :     if (is_master_)
    1574         220 :         return;
    1575             : 
    1576          34 :     CHECK_CONCURRENCY("bgp::Config", "bgp::ConfigHelper");
    1577         170 :     BOOST_FOREACH(RouteTarget rtarget, import_) {
    1578          68 :         DeleteRTargetRoute(asn, rtarget);
    1579             :     }
    1580             : }
    1581             : 
    1582          68 : void RoutingInstance::ProcessIdentifierUpdate(as_t asn) {
    1583          68 :     FlushAllRTargetRoutes(asn);
    1584          68 :     InitAllRTargetRoutes(asn);
    1585          68 :     rd_.reset(new RouteDistinguisher(server_->bgp_identifier(), index_));
    1586          68 : }
    1587             : 
    1588           0 : void RoutingInstance::AddRouteTarget(bool import,
    1589             :     vector<string> *change_list, RouteTargetList::const_iterator it) {
    1590           0 :     BgpTable *ermvpn_table = GetTable(Address::ERMVPN);
    1591             :     RoutePathReplicator *ermvpn_replicator =
    1592           0 :         server_->replicator(Address::ERMVPN);
    1593           0 :     BgpTable *mvpn_table = GetTable(Address::MVPN);
    1594             :     RoutePathReplicator *mvpn_replicator =
    1595           0 :         server_->replicator(Address::MVPN);
    1596           0 :     BgpTable *evpn_table = GetTable(Address::EVPN);
    1597             :     RoutePathReplicator *evpn_replicator =
    1598           0 :         server_->replicator(Address::EVPN);
    1599           0 :     BgpTable *inet_table = GetTable(Address::INET);
    1600             :     RoutePathReplicator *inetvpn_replicator =
    1601           0 :         server_->replicator(Address::INETVPN);
    1602           0 :     BgpTable *inet6_table = GetTable(Address::INET6);
    1603             :     RoutePathReplicator *inet6vpn_replicator =
    1604           0 :         server_->replicator(Address::INET6VPN);
    1605             : 
    1606           0 :     change_list->push_back(it->ToString());
    1607           0 :     if (import) {
    1608           0 :         import_.insert(*it);
    1609           0 :         if (server_->local_autonomous_system() != 0 && always_subscribe_)
    1610           0 :             AddRTargetRoute(server_->local_autonomous_system(), *it);
    1611             :     } else {
    1612           0 :         export_.insert(*it);
    1613             :     }
    1614             : 
    1615           0 :     ermvpn_replicator->Join(ermvpn_table, *it, import);
    1616           0 :     mvpn_replicator->Join(mvpn_table, *it, import);
    1617           0 :     evpn_replicator->Join(evpn_table, *it, import);
    1618           0 :     inetvpn_replicator->Join(inet_table, *it, import);
    1619           0 :     inet6vpn_replicator->Join(inet6_table, *it, import);
    1620           0 : }
    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         102 : void RoutingInstance::ClearRouteTarget() {
    1656         102 :     CHECK_CONCURRENCY("bgp::Config");
    1657         102 :     if (IsMasterRoutingInstance()) {
    1658          68 :         return;
    1659             :     }
    1660             : 
    1661          34 :     ClearFamilyRouteTarget(Address::INET, Address::INETVPN);
    1662          34 :     ClearFamilyRouteTarget(Address::INET6, Address::INET6VPN);
    1663          34 :     ClearFamilyRouteTarget(Address::ERMVPN, Address::ERMVPN);
    1664          34 :     ClearFamilyRouteTarget(Address::MVPN, Address::MVPN);
    1665          34 :     ClearFamilyRouteTarget(Address::EVPN, Address::EVPN);
    1666             : 
    1667          34 :     import_.clear();
    1668          34 :     export_.clear();
    1669             : }
    1670             : 
    1671          68 : BgpTable *RoutingInstance::RTargetTableCreate() {
    1672             :     BgpTable *rtargettbl = static_cast<BgpTable *>(
    1673          68 :         server_->database()->CreateTable("bgp.rtarget.0"));
    1674          68 :     RTINSTANCE_LOG_TABLE(Create, this, rtargettbl, SandeshLevel::SYS_DEBUG,
    1675             :                          RTINSTANCE_LOG_FLAG_ALL);
    1676          68 :     AddTable(rtargettbl);
    1677          68 :     return rtargettbl;
    1678             : }
    1679             : 
    1680         340 : BgpTable *RoutingInstance::VpnTableCreate(Address::Family vpn_family) {
    1681         340 :     string table_name = GetTableName(name(), vpn_family);
    1682             :     BgpTable *table = static_cast<BgpTable *>(
    1683         340 :         server_->database()->CreateTable(table_name));
    1684         340 :     assert(table);
    1685             : 
    1686         340 :     AddTable(table);
    1687         340 :     RTINSTANCE_LOG_TABLE(Create, this, table, SandeshLevel::SYS_DEBUG,
    1688             :         RTINSTANCE_LOG_FLAG_ALL);
    1689         340 :     assert(server_->rtarget_group_mgr()->empty());
    1690         340 :     RoutePathReplicator *replicator = server_->replicator(vpn_family);
    1691         340 :     replicator->Initialize();
    1692         340 :     return table;
    1693         340 : }
    1694             : 
    1695         170 : BgpTable *RoutingInstance::VrfTableCreate(Address::Family vrf_family,
    1696             :     Address::Family vpn_family) {
    1697         170 :     string table_name = GetTableName(name(), vrf_family);
    1698             :     BgpTable *table = static_cast<BgpTable *>(
    1699         170 :         server_->database()->CreateTable(table_name));
    1700         170 :     assert(table);
    1701             : 
    1702         170 :     AddTable(table);
    1703         170 :     RTINSTANCE_LOG_TABLE(Create, this, table, SandeshLevel::SYS_DEBUG,
    1704             :         RTINSTANCE_LOG_FLAG_ALL);
    1705         170 :     RoutePathReplicator *replicator = server_->replicator(vpn_family);
    1706         850 :     BOOST_FOREACH(RouteTarget rt, import_) {
    1707         340 :         replicator->Join(table, rt, true);
    1708             :     }
    1709         510 :     BOOST_FOREACH(RouteTarget rt, export_) {
    1710         170 :         replicator->Join(table, rt, false);
    1711             :     }
    1712         170 :     return table;
    1713         170 : }
    1714             : 
    1715         782 : void RoutingInstance::AddTable(BgpTable *tbl) {
    1716         782 :     vrf_tables_by_name_.insert(make_pair(tbl->name(), tbl));
    1717         782 :     vrf_tables_by_family_.insert(make_pair(tbl->family(), tbl));
    1718         782 :     tbl->set_routing_instance(this);
    1719         782 :     RoutingInstanceInfo info = GetDataCollection("Add");
    1720         782 :     info.set_family(Address::FamilyToString(tbl->family()));
    1721         782 :     ROUTING_INSTANCE_COLLECTOR_INFO(info);
    1722         782 : }
    1723             : 
    1724         782 : void RoutingInstance::RemoveTable(BgpTable *tbl) {
    1725         782 :     RoutingInstanceInfo info = GetDataCollection("Remove");
    1726         782 :     info.set_family(Address::FamilyToString(tbl->family()));
    1727         782 :     vrf_tables_by_name_.erase(tbl->name());
    1728         782 :     vrf_tables_by_family_.erase(tbl->family());
    1729         782 :     ROUTING_INSTANCE_COLLECTOR_INFO(info);
    1730         782 : }
    1731             : 
    1732             : //
    1733             : // Concurrency: BGP Config task
    1734             : //
    1735             : // Remove the table from the map and delete the table data structure
    1736             : //
    1737         782 : void RoutingInstance::DestroyDBTable(DBTable *dbtable) {
    1738         782 :     CHECK_CONCURRENCY("bgp::Config");
    1739             : 
    1740         782 :     BgpTable *table = static_cast<BgpTable *>(dbtable);
    1741             : 
    1742         782 :     RTINSTANCE_LOG_TABLE(Destroy, this, table,
    1743             :         SandeshLevel::SYS_DEBUG, RTINSTANCE_LOG_FLAG_ALL);
    1744             : 
    1745             :     // Remove this table from various data structures
    1746         782 :     server_->database()->RemoveTable(table);
    1747         782 :     RemoveTable(table);
    1748             : 
    1749             :     // Make sure that there are no routes left in this table
    1750         782 :     assert(table->Size() == 0);
    1751             : 
    1752         782 :     delete table;
    1753         782 : }
    1754             : 
    1755         524 : string RoutingInstance::GetTableName(string instance_name,
    1756             :     Address::Family fmly) {
    1757         524 :     string table_name;
    1758         524 :     if (instance_name == BgpConfigManager::kMasterInstance) {
    1759         340 :         if ((fmly == Address::INET) || (fmly == Address::INET6)) {
    1760           0 :             table_name = Address::FamilyToTableString(fmly) + ".0";
    1761         340 :         } else if (fmly == Address::INETMPLS) {
    1762           0 :             table_name = Address::FamilyToTableString(fmly) + ".3";
    1763             :         } else {
    1764         340 :             table_name = "bgp." + Address::FamilyToTableString(fmly) + ".0";
    1765             :         }
    1766             :     } else {
    1767             :         table_name =
    1768         184 :             instance_name + "." + Address::FamilyToTableString(fmly) + ".0";
    1769             :     }
    1770         524 :     return table_name;
    1771           0 : }
    1772             : 
    1773       14508 : BgpTable *RoutingInstance::GetTable(Address::Family fmly) {
    1774       14508 :     RouteTableFamilyList::const_iterator loc = vrf_tables_by_family_.find(fmly);
    1775       14504 :     return (loc != vrf_tables_by_family_.end() ? loc->second : NULL);
    1776             : }
    1777             : 
    1778         130 : const BgpTable *RoutingInstance::GetTable(Address::Family fmly) const {
    1779         130 :     RouteTableFamilyList::const_iterator loc = vrf_tables_by_family_.find(fmly);
    1780         130 :     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         102 : void RoutingInstance::set_index(int index) {
    1805         102 :     index_ = index;
    1806         102 :     if (is_master_)
    1807          68 :         return;
    1808             : 
    1809          34 :     rd_.reset(new RouteDistinguisher(server_->bgp_identifier(), index));
    1810             : }
    1811             : 
    1812        1768 : RoutingInstanceInfo RoutingInstance::GetDataCollection(const char *operation) {
    1813        3536 :     RoutingInstanceInfo info;
    1814        1768 :     info.set_name(GetVirtualNetworkName());
    1815        1768 :     info.set_instance_name(name_);
    1816        1768 :     info.set_hostname(server_->localname());
    1817        1768 :     if (rd_.get()) info.set_route_distinguisher(rd_->ToString());
    1818        1768 :     if (operation) info.set_operation(operation);
    1819        1768 :     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           0 : bool RoutingInstance::IsServiceChainRoute(const BgpRoute *route) const {
    1844           0 :     const BgpTable *table = route->table();
    1845           0 :     if (!table) {
    1846           0 :         return false;
    1847             :     }
    1848           0 :     const BgpInstanceConfig *rt_config = this->config();
    1849           0 :     if (!rt_config) {
    1850           0 :         return false;
    1851             :     }
    1852             :     SCAddress::Family sc_family =
    1853           0 :         SCAddress::AddressFamilyToSCFamily(table->family());
    1854             :     const ServiceChainConfig *sc_config =
    1855           0 :            rt_config->service_chain_info(sc_family);
    1856           0 :     if (!sc_config) {
    1857           0 :         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        3443 : bool RoutingInstance::ProcessRoutingPolicy(const BgpRoute *route,
    1870             :                                            BgpPath *path) const {
    1871        3443 :     ExtCommunityPtr ext_community = path->GetOriginalAttr()->ext_community();
    1872        3434 :     if (path->IsReplicated() &&
    1873        3434 :             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        3435 :     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        3436 :     const RoutingPolicyMgr *policy_mgr = server()->routing_policy_mgr();
    1891             :     // Take snapshot of original attribute
    1892        3442 :     BgpAttr *out_attr = new BgpAttr(*(path->GetOriginalAttr()));
    1893        3453 :     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        3431 :     IPeer *peer = path->GetPeer();
    1928        3431 :     if (peer) {
    1929        6290 :         peer->ProcessPathTunnelEncapsulation(path, out_attr,
    1930        3147 :             server_->extcomm_db(), route->table());
    1931             :     }
    1932        3435 :     BgpAttrPtr modified_attr = server_->attr_db()->Locate(out_attr);
    1933        3454 :     path->SetAttr(modified_attr, path->GetOriginalAttr());
    1934             :     // Clear the reject if marked so in past
    1935        3454 :     if (path->IsPolicyReject()) path->ResetPolicyReject();
    1936        3454 :     return true;
    1937        3454 : }
    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        6977 : bool RoutingInstance::IsContributingRoute(const BgpTable *table,
    1994             :                                           const BgpRoute *route) const {
    1995        6977 :     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         285 : PeerManager *RoutingInstance::LocatePeerManager() {
    2018         285 :     if (!peer_manager_)
    2019          85 :         peer_manager_.reset(BgpStaticObjectFactory::Create<PeerManager>(this));
    2020         285 :     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