Bug 5558 - Closing session after a large RIB is sent kills BGPCEP
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPPeer.java
index d9942cb1881d109c22e45766fe956bf1d3814e9c..a40eef1ef28ffa129e5d6e88a436728500f2105c 100644 (file)
@@ -14,8 +14,10 @@ import com.google.common.collect.Lists;
 import com.google.common.net.InetAddresses;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 import javax.annotation.concurrent.GuardedBy;
 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean;
@@ -28,13 +30,16 @@ import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
+import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
+import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStatistics;
 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
-import org.opendaylight.protocol.bgp.rib.impl.spi.ReusableBGPPeer;
 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
+import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
 import org.opendaylight.protocol.bgp.rib.spi.Peer;
+import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.DestinationIpv4Builder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4Prefixes;
@@ -46,17 +51,25 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.mess
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.Attributes1;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.Attributes2;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.RouteRefresh;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlri;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlriBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlri;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlriBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev160322.BgpPeerRpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev160322.PeerContext;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.PeerKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.SubsequentAddressFamily;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
+import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.Notification;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -65,7 +78,7 @@ import org.slf4j.LoggerFactory;
  * Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into
  * RIB actions.
  */
-public class BGPPeer implements ReusableBGPPeer, Peer, AutoCloseable, BGPPeerRuntimeMXBean, TransactionChainListener {
+public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeerRuntimeMXBean, TransactionChainListener {
 
     private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class);
 
@@ -85,33 +98,55 @@ public class BGPPeer implements ReusableBGPPeer, Peer, AutoCloseable, BGPPeerRun
     private BGPPeerRuntimeRegistrator registrator;
     private BGPPeerRuntimeRegistration runtimeReg;
     private long sessionEstablishedCounter = 0L;
+    private final Map<TablesKey, AdjRibOutListener> adjRibOutListenerSet = new HashMap();
+    private final RpcProviderRegistry rpcRegistry;
+    private RoutedRpcRegistration<BgpPeerRpcService> rpcRegistration;
+    private final PeerRole peerRole;
 
-    public BGPPeer(final String name, final RIB rib) {
-        this(name, rib, PeerRole.Ibgp);
-    }
-
-    public BGPPeer(final String name, final RIB rib, final PeerRole role) {
+    public BGPPeer(final String name, final RIB rib, final PeerRole role, final RpcProviderRegistry rpcRegistry) {
+        this.peerRole = role;
         this.rib = Preconditions.checkNotNull(rib);
         this.name = name;
         this.chain = rib.createPeerChain(this);
         this.ribWriter = AdjRibInWriter.create(rib.getYangRibId(), role, this.chain);
+        this.rpcRegistry = rpcRegistry;
     }
 
     @Override
     public synchronized void close() {
-        dropConnection();
+        releaseConnection();
         this.chain.close();
-        // TODO should this perform cleanup ?
     }
 
     @Override
     public void onMessage(final BGPSession session, final Notification msg) {
-        if (!(msg instanceof Update)) {
+        if (!(msg instanceof Update) && !(msg instanceof RouteRefresh)) {
             LOG.info("Ignoring unhandled message class {}", msg.getClass());
             return;
         }
-        final Update message = (Update) msg;
+        if (msg instanceof Update) {
+            onUpdateMessage((Update) msg);
+        } else {
+            onRouteRefreshMessage((RouteRefresh) msg, session);
+        }
+    }
+
+    private void onRouteRefreshMessage(final RouteRefresh message, final BGPSession session) {
+        final Class<? extends AddressFamily> rrAfi = message.getAfi();
+        final Class<? extends SubsequentAddressFamily> rrSafi = message.getSafi();
+
+        final TablesKey key = new TablesKey(rrAfi, rrSafi);
+        final AdjRibOutListener listener = this.adjRibOutListenerSet.get(key);
+        if (listener != null) {
+            listener.close();
+            this.adjRibOutListenerSet.remove(listener);
+            createAdjRibOutListener(RouterIds.createPeerId(session.getBgpId()), key, true);
+        } else {
+            LOG.info("Ignoring RouteRefresh message. Afi/Safi is not supported: {}, {}.", rrAfi, rrSafi);
+        }
+    }
 
+    private void onUpdateMessage(final Update message) {
         // update AdjRibs
         final Attributes attrs = message.getAttributes();
         MpReachNlri mpReach = null;
@@ -193,25 +228,45 @@ public class BGPPeer implements ReusableBGPPeer, Peer, AutoCloseable, BGPPeerRun
 
     @Override
     public synchronized void onSessionUp(final BGPSession session) {
-        LOG.info("Session with peer {} went up with tables: {}", this.name, session.getAdvertisedTableTypes());
+        final List<AddressFamilies> addPathTablesType = session.getAdvertisedAddPathTableTypes();
+        LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name, addPathTablesType,
+            session.getAdvertisedAddPathTableTypes());
         this.session = session;
+
         this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress();
         final PeerId peerId = RouterIds.createPeerId(session.getBgpId());
-        TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
-        this.tables.add(key);
-        createAdjRibOutListener(peerId, key, false);
+        createAdjRibOutListener(peerId);
+
+        this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, addPathTablesType, false);
+        this.sessionEstablishedCounter++;
+        if (this.registrator != null) {
+            this.runtimeReg = this.registrator.register(this);
+        }
 
-        for (final BgpTableType t : session.getAdvertisedTableTypes()) {
-            key = new TablesKey(t.getAfi(), t.getSafi());
+        if (this.rpcRegistry != null) {
+            this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class, new BgpPeerRpc(session, this.tables));
+            final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer, PeerKey> path =
+                this.rib.getInstanceIdentifier().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer.class, new PeerKey(peerId));
+            this.rpcRegistration.registerPath(PeerContext.class, path);
+        }
+    }
+
+    private void createAdjRibOutListener(final PeerId peerId) {
+        for (final BgpTableType t : this.session.getAdvertisedTableTypes()) {
+            final TablesKey key = new TablesKey(t.getAfi(), t.getSafi());
             if (this.tables.add(key)) {
                 createAdjRibOutListener(peerId, key, true);
             }
         }
 
-        this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, false);
-        this.sessionEstablishedCounter++;
-        if (this.registrator != null) {
-            this.runtimeReg = this.registrator.register(this);
+        addBgp4Support(peerId);
+    }
+
+    //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
+    private void addBgp4Support(final PeerId peerId) {
+        final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
+        if (this.tables.add(key)) {
+            createAdjRibOutListener(peerId, key, false);
         }
     }
 
@@ -220,20 +275,28 @@ public class BGPPeer implements ReusableBGPPeer, Peer, AutoCloseable, BGPPeerRun
 
         // not particularly nice
         if (context != null && this.session instanceof BGPSessionImpl) {
-            AdjRibOutListener.create(peerId, key, this.rib.getYangRibId(), this.rib.getCodecsRegistry(), context.getRibSupport(), ((RIBImpl) this.rib).getService(),
-                ((BGPSessionImpl) this.session).getLimiter(), mpSupport);
+            this.adjRibOutListenerSet.put(key, AdjRibOutListener.create(peerId, key, this.rib.getYangRibId(), this.rib.getCodecsRegistry(),
+                context.getRibSupport(), ((RIBImpl) this.rib).getService(), ((BGPSessionImpl) this.session).getLimiter(), mpSupport));
         }
     }
 
     private synchronized void cleanup() {
-        // FIXME: BUG-196: support graceful restart
-        this.ribWriter.cleanTables(this.tables);
+        // FIXME: BUG-196: support graceful
+        for (final AdjRibOutListener adjRibOutListener : this.adjRibOutListenerSet.values()) {
+            adjRibOutListener.close();
+        }
+        this.adjRibOutListenerSet.clear();
+        this.ribWriter.removePeer();
         this.tables.clear();
     }
 
     @Override
     public void onSessionDown(final BGPSession session, final Exception e) {
-        LOG.info("Session with peer {} went down", this.name, e);
+        if(e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
+            LOG.info("Session with peer {} went down", this.name);
+        } else {
+            LOG.info("Session with peer {} went down", this.name, e);
+        }
         releaseConnection();
     }
 
@@ -261,8 +324,18 @@ public class BGPPeer implements ReusableBGPPeer, Peer, AutoCloseable, BGPPeerRun
 
     @Override
     public void releaseConnection() {
-        dropConnection();
+        if (this.rpcRegistration != null) {
+            this.rpcRegistration.close();
+        }
+        addPeerToDisconnectedSharedList();
         cleanup();
+        dropConnection();
+    }
+
+    private void addPeerToDisconnectedSharedList() {
+        if(this.session != null) {
+            this.rib.getCacheDisconnectedPeers().insertDesconectedPeer(this.session.getBgpId());
+        }
     }
 
     @GuardedBy("this")
@@ -333,9 +406,10 @@ public class BGPPeer implements ReusableBGPPeer, Peer, AutoCloseable, BGPPeerRun
     @Override
     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
         LOG.error("Transaction chain failed.", cause);
-        dropConnection();
         this.chain.close();
         this.chain = this.rib.createPeerChain(this);
+        this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.chain);
+        releaseConnection();
     }
 
     @Override