BGPCEP-754: Rework EffectiveRibInWriter
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPPeer.java
index 71b67bd32767e5db8672158071ef1ac19ca43cba..b5cb557f3c3325bf13e149ba7763641a093fc62d 100644 (file)
@@ -8,10 +8,7 @@
 package org.opendaylight.protocol.bgp.rib.impl;
 
 import static java.util.Objects.requireNonNull;
-import static org.opendaylight.protocol.bgp.rib.impl.AdjRibInWriter.isAnnounceNone;
-import static org.opendaylight.protocol.bgp.rib.impl.AdjRibInWriter.isLearnNone;
 
-import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.MoreObjects;
 import com.google.common.base.MoreObjects.ToStringHelper;
 import com.google.common.base.Objects;
@@ -21,6 +18,7 @@ import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
@@ -28,7 +26,6 @@ import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
-import javax.annotation.Nonnull;
 import javax.annotation.concurrent.GuardedBy;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
@@ -51,6 +48,7 @@ import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
 import org.opendaylight.protocol.bgp.rib.spi.Peer;
 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
+import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters;
 import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
 import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
@@ -82,7 +80,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev171207.PeerContext;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerRole;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.SimpleRoutingPolicy;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.PeerKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.TablesKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily;
@@ -99,7 +96,8 @@ 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 extends BGPPeerStateImpl implements BGPSessionListener, Peer, TransactionChainListener {
+public class BGPPeer extends BGPPeerStateImpl implements BGPRouteEntryImportParameters,
+        BGPSessionListener, Peer, TransactionChainListener {
     private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class);
 
     @GuardedBy("this")
@@ -109,9 +107,14 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
     private final Map<TablesKey, AdjRibOutListener> adjRibOutListenerSet = new HashMap<>();
     private final RpcProviderRegistry rpcRegistry;
     private final PeerRole peerRole;
-    private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
+    private final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib
+            .rev171207.bgp.rib.rib.Peer, PeerKey> peerIId;
+    @GuardedBy("this")
+    private AbstractRegistration trackerRegistration;
     @GuardedBy("this")
     private final Set<AbstractRegistration> tableRegistration = new HashSet<>();
+    private final PeerId peerId;
+    private final YangInstanceIdentifier peerYIId;
     @GuardedBy("this")
     private BGPSession session;
     @GuardedBy("this")
@@ -123,27 +126,25 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
     @GuardedBy("this")
     private EffectiveRibInWriter effRibInWriter;
     private RoutedRpcRegistration<BgpPeerRpcService> rpcRegistration;
+    private Map<TablesKey, SendReceive> addPathTableMaps = Collections.emptyMap();
 
     public BGPPeer(final IpAddress neighborAddress, final RIB rib, final PeerRole role,
-            final SimpleRoutingPolicy peerStatus, final RpcProviderRegistry rpcRegistry,
-            @Nonnull final Set<TablesKey> afiSafisAdvertized,
-            @Nonnull final Set<TablesKey> afiSafisGracefulAdvertized) {
+            final RpcProviderRegistry rpcRegistry,
+            final Set<TablesKey> afiSafisAdvertized,
+            final Set<TablesKey> afiSafisGracefulAdvertized) {
         //FIXME BUG-6971 Once Peer Group is implemented, pass it
         super(rib.getInstanceIdentifier(), null, neighborAddress, afiSafisAdvertized,
                 afiSafisGracefulAdvertized);
         this.peerRole = role;
-        this.simpleRoutingPolicy = Optional.ofNullable(peerStatus);
         this.rib = requireNonNull(rib);
         this.name = Ipv4Util.toStringIP(neighborAddress);
         this.rpcRegistry = rpcRegistry;
-        this.chain = rib.createPeerChain(this);
-    }
-
-    @VisibleForTesting
-    BGPPeer(final IpAddress neighborAddress, final RIB rib, final PeerRole role,
-            final RpcProviderRegistry rpcRegistry, @Nonnull final Set<TablesKey> afiSafisAdvertized,
-            @Nonnull final Set<TablesKey> afiSafisGracefulAdvertized) {
-        this(neighborAddress, rib, role, null, rpcRegistry, afiSafisAdvertized, afiSafisGracefulAdvertized);
+        this.peerId = RouterIds.createPeerId(neighborAddress);
+        this.peerIId = getInstanceIdentifier().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns
+                .yang.bgp.rib.rev171207.bgp.rib.rib.Peer.class, new PeerKey(this.peerId));
+        this.peerYIId = this.rib.getYangRibId().node(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang
+                .bgp.rib.rev171207.bgp.rib.rib.Peer.QNAME).node(IdentifierUtils.domPeerId(this.peerId));
+        this.chain = rib.createPeerDOMChain(this);
     }
 
     private static Attributes nextHopToAttribute(final Attributes attrs, final MpReachNlri mpReach) {
@@ -211,8 +212,7 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
     }
 
     public synchronized void instantiateServiceInstance() {
-        this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy,
-                this.chain);
+        this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.chain);
         setActive(true);
     }
 
@@ -234,11 +234,11 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
         if (msg instanceof Update) {
             onUpdateMessage((Update) msg);
         } else {
-            onRouteRefreshMessage((RouteRefresh) msg, session);
+            onRouteRefreshMessage((RouteRefresh) msg);
         }
     }
 
-    private void onRouteRefreshMessage(final RouteRefresh message, final BGPSession session) {
+    private void onRouteRefreshMessage(final RouteRefresh message) {
         final Class<? extends AddressFamily> rrAfi = message.getAfi();
         final Class<? extends SubsequentAddressFamily> rrSafi = message.getSafi();
 
@@ -247,7 +247,7 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
         if (listener != null) {
             listener.close();
             this.adjRibOutListenerSet.remove(key);
-            createAdjRibOutListener(RouterIds.createPeerId(session.getBgpId()), key, listener.isMpSupported());
+            createAdjRibOutListener(key, listener.isMpSupported());
         } else {
             LOG.info("Ignoring RouteRefresh message. Afi/Safi is not supported: {}, {}.", rrAfi, rrSafi);
         }
@@ -280,7 +280,7 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
 
         // update AdjRibs
         final Attributes attrs = message.getAttributes();
-        MpReachNlri mpReach = null;
+        MpReachNlri mpReach;
         final boolean isAnyNlriAnnounced = message.getNlri() != null;
         if (isAnyNlriAnnounced) {
             mpReach = prefixesToMpReach(message);
@@ -290,7 +290,7 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
         if (mpReach != null) {
             this.ribWriter.updateRoutes(mpReach, nextHopToAttribute(attrs, mpReach));
         }
-        MpUnreachNlri mpUnreach = null;
+        MpUnreachNlri mpUnreach;
         if (message.getWithdrawnRoutes() != null) {
             mpUnreach = prefixesToMpUnreach(message, isAnyNlriAnnounced);
         } else {
@@ -307,53 +307,37 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
         if (this.session instanceof BGPSessionStateProvider) {
             ((BGPSessionStateProvider) this.session).registerMessagesCounter(this);
         }
-
         final List<AddressFamilies> addPathTablesType = session.getAdvertisedAddPathTableTypes();
         final Set<BgpTableType> advertizedTableTypes = session.getAdvertisedTableTypes();
         final List<BgpTableType> advertizedGracefulRestartTableTypes = session.getAdvertisedGracefulRestartTableTypes();
         LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name,
                 advertizedTableTypes, addPathTablesType);
         this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress();
-        final PeerId peerId = RouterIds.createPeerId(session.getBgpId());
-
         this.tables.addAll(advertizedTableTypes.stream().map(t -> new TablesKey(t.getAfi(), t.getSafi()))
                 .collect(Collectors.toList()));
 
         setAdvertizedGracefulRestartTableTypes(advertizedGracefulRestartTableTypes.stream()
                 .map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList()));
-        final boolean announceNone = isAnnounceNone(this.simpleRoutingPolicy);
-        final Map<TablesKey, SendReceive> addPathTableMaps = mapTableTypesFamilies(addPathTablesType);
+        this.addPathTableMaps = mapTableTypesFamilies(addPathTablesType);
 
-        if (!announceNone) {
-            for (final TablesKey key : this.tables) {
-                createAdjRibOutListener(peerId, key, true);
-            }
+        for (final TablesKey key : this.tables) {
+            createAdjRibOutListener(key, true);
         }
 
-        final YangInstanceIdentifier peerIId = this.rib.getYangRibId()
-                .node(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang
-                        .bgp.rib.rev171207.bgp.rib.rib.Peer.QNAME).node(IdentifierUtils.domPeerId(peerId));
-
         for(final TablesKey tablesKey :this.tables) {
             final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(tablesKey);
             if (exportTracker != null) {
-                this.tableRegistration.add(exportTracker.registerPeer(peerId, addPathTableMaps.get(tablesKey),
-                        peerIId, this.peerRole, this.simpleRoutingPolicy));
+                this.tableRegistration.add(exportTracker.registerPeer(this.peerId, this.addPathTableMaps.get(tablesKey),
+                        this.peerYIId, this.peerRole));
             }
         }
-        addBgp4Support(peerId, announceNone);
-
-        if (!isLearnNone(this.simpleRoutingPolicy)) {
-            this.effRibInWriter = EffectiveRibInWriter.create(this.rib.getService(),
-                    this.rib.createPeerChain(this),
-                    peerIId, this.rib.getImportPolicyPeerTracker(),
-                    this.rib.getRibSupportContext(),
-                    this.peerRole,
-                    this.tables);
-            registerPrefixesCounters(this.effRibInWriter, this.effRibInWriter);
-        }
-        this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables,
-                addPathTableMaps);
+        addBgp4Support();
+
+        this.effRibInWriter = EffectiveRibInWriter.create(this, this.rib, this.rib.createPeerChain(this),
+                this.peerIId, this.tables);
+        registerPrefixesCounters(this.effRibInWriter, this.effRibInWriter);
+        this.ribWriter = this.ribWriter.transform(this.peerId, this.rib.getRibSupportContext(), this.tables,
+                this.addPathTableMaps);
 
         if (this.rpcRegistry != null) {
             this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class,
@@ -361,27 +345,33 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
             final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib
                     .rev171207.bgp.rib.rib.Peer, PeerKey> path = this.rib.getInstanceIdentifier()
                     .child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib
-                             .rib.Peer.class, new PeerKey(peerId));
+                             .rib.Peer.class, new PeerKey(this.peerId));
             this.rpcRegistration.registerPath(PeerContext.class, path);
         }
+        this.trackerRegistration = this.rib.getPeerTracker().registerPeer(this);
     }
 
     //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 boolean announceNone) {
+    private void addBgp4Support() {
         final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
-        if (this.tables.add(key) && !announceNone) {
-            createAdjRibOutListener(peerId, key, false);
+        if (this.tables.add(key)) {
+            createAdjRibOutListener(key, false);
+            final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(key);
+            if (exportTracker != null) {
+                this.tableRegistration.add(exportTracker.registerPeer(peerId,  null, this.peerYIId,
+                        this.peerRole));
+            }
         }
     }
 
-    private synchronized void createAdjRibOutListener(final PeerId peerId, final TablesKey key,
+    private synchronized void createAdjRibOutListener(final TablesKey key,
             final boolean mpSupport) {
         final RIBSupportContext context = this.rib.getRibSupportContext().getRIBSupportContext(key);
 
         // not particularly nice
         if (context != null && this.session instanceof BGPSessionImpl) {
             final ChannelOutputLimiter limiter = ((BGPSessionImpl) this.session).getLimiter();
-            final AdjRibOutListener adjRibOut = AdjRibOutListener.create(peerId, key,
+            final AdjRibOutListener adjRibOut = AdjRibOutListener.create(this.peerId, key,
                     this.rib.getYangRibId(), this.rib.getCodecsRegistry(), context.getRibSupport(),
                     this.rib.getService(), limiter, mpSupport);
             this.adjRibOutListenerSet.put(key, adjRibOut);
@@ -459,6 +449,10 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
     private void closeRegistration() {
         this.tableRegistration.iterator().forEachRemaining(AbstractRegistration::close);
         this.tableRegistration.clear();
+        if (this.trackerRegistration != null) {
+            this.trackerRegistration.close();
+            this.trackerRegistration = null;
+        }
     }
 
     @Override
@@ -466,20 +460,44 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
     }
 
+    @Override
+    public PeerId getPeerId() {
+        return this.peerId;
+    }
+
+    @Override
+    public SendReceive getSupportedAddPathTables(final TablesKey tableKey) {
+        return this.addPathTableMaps.get(tableKey);
+    }
+
+    @Override
+    public boolean supportsTable(final TablesKey tableKey) {
+        return this.tables.contains(tableKey);
+    }
+
+    @Override
+    public YangInstanceIdentifier getPeerRibInstanceIdentifier() {
+        return this.peerYIId;
+    }
+
+    @Override
+    public PeerRole getRole() {
+        return this.peerRole;
+    }
+
     @Override
     public synchronized void onTransactionChainFailed(final TransactionChain<?, ?> chain,
             final AsyncTransaction<?, ?> transaction, final Throwable cause) {
         LOG.error("Transaction chain failed.", cause);
         this.chain.close();
-        this.chain = this.rib.createPeerChain(this);
-        this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy,
-                this.chain);
+        this.chain = this.rib.createPeerDOMChain(this);
+        this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.chain);
         releaseConnection();
     }
 
     @Override
     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
-        LOG.debug("Transaction chain {} successfull.", chain);
+        LOG.debug("Transaction chain {} successful.", chain);
     }
 
     @Override
@@ -520,4 +538,14 @@ public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Pee
         }
         return null;
     }
+
+    @Override
+    public PeerRole getFromPeerRole() {
+        return getRole();
+    }
+
+    @Override
+    public PeerId getFromPeerId() {
+        return getPeerId();
+    }
 }