Fix an eclipse nullness warning
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / LocRibWriter.java
index d6ad73ec11dc13f2cd878eb620196f5230fda660..5e03801026c463677e885be523ace22a1951405b 100644 (file)
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
+import static java.util.Objects.requireNonNull;
+
 import com.google.common.primitives.UnsignedInteger;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.MoreExecutors;
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.atomic.LongAdder;
 import javax.annotation.Nonnull;
+import javax.annotation.concurrent.GuardedBy;
 import javax.annotation.concurrent.NotThreadSafe;
+import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
+import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
-import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
+import org.opendaylight.mdsal.common.api.CommitInfo;
 import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
 import org.opendaylight.protocol.bgp.mode.api.RouteEntry;
-import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
-import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
-import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
-import org.opendaylight.protocol.bgp.rib.spi.PeerExportGroup;
+import org.opendaylight.protocol.bgp.rib.impl.spi.RibOutRefresh;
+import org.opendaylight.protocol.bgp.rib.impl.state.rib.TotalPathsCounter;
+import org.opendaylight.protocol.bgp.rib.impl.state.rib.TotalPrefixesCounter;
+import org.opendaylight.protocol.bgp.rib.spi.BGPPeerTracker;
 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
-import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
+import org.opendaylight.protocol.bgp.rib.spi.entry.ActualBestPathRoutes;
+import org.opendaylight.protocol.bgp.rib.spi.entry.AdvertizedRoute;
+import org.opendaylight.protocol.bgp.rib.spi.entry.StaleBestPathRoute;
+import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
+import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.AfiSafiType;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
-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.LocRib;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
-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.rib.rev130925.rib.tables.Attributes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Routes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.Rib;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.RibKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.LocRib;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.Peer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.PeerKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.EffectiveRibIn;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Attributes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.AttributesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Routes;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.binding.ChildOf;
+import org.opendaylight.yangtools.yang.binding.ChoiceIn;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.Identifiable;
+import org.opendaylight.yangtools.yang.binding.Identifier;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 @NotThreadSafe
-final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeListener {
+final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
+        R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>>
+        implements AutoCloseable, RibOutRefresh, TotalPrefixesCounter, TotalPathsCounter,
+        ClusteredDataTreeChangeListener<Tables> {
 
     private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
 
-    private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "uptodate"), Boolean.TRUE);
-
-    private final Map<PathArgument, RouteEntry> routeEntries = new HashMap<>();
-    private final YangInstanceIdentifier locRibTarget;
-    private final DOMTransactionChain chain;
-    private final ExportPolicyPeerTracker exportPolicyPeerTracker;
-    private final NodeIdentifier attributesIdentifier;
+    private final Map<String, RouteEntry<C,S,R,I>> routeEntries = new HashMap<>();
     private final Long ourAs;
-    private final RIBSupport ribSupport;
-    private final TablesKey localTablesKey;
-    private final ListenerRegistration<LocRibWriter> reg;
+    private final RIBSupport<C,S,R,I> ribSupport;
+    private final DataBroker dataBroker;
     private final PathSelectionMode pathSelectionMode;
-    private final LongAdder routeCounter;
-
-    private LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target,
-        final Long ourAs, final DOMDataTreeChangeService service, final ExportPolicyPeerTracker exportPolicyPeerTracker, final TablesKey tablesKey,
-        @Nonnull final PathSelectionMode pathSelectionMode, final LongAdder routeCounter) {
-        this.chain = Preconditions.checkNotNull(chain);
-        final NodeIdentifierWithPredicates tableKey = RibSupportUtils.toYangTablesKey(tablesKey);
-        this.localTablesKey = tablesKey;
-        this.locRibTarget = YangInstanceIdentifier.create(target.node(LocRib.QNAME).node(Tables.QNAME).node(tableKey).getPathArguments());
-        this.ourAs = Preconditions.checkNotNull(ourAs);
-        this.ribSupport = registry.getRIBSupportContext(tablesKey).getRibSupport();
-        this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier();
-        this.exportPolicyPeerTracker = exportPolicyPeerTracker;
+    private final LongAdder totalPathsCounter = new LongAdder();
+    private final LongAdder totalPrefixesCounter = new LongAdder();
+    private final RouteEntryDependenciesContainerImpl entryDep;
+    private final BGPPeerTracker peerTracker;
+    private final KeyedInstanceIdentifier<Rib, RibKey> ribIId;
+    private final TablesKey tk;
+    private final KeyedInstanceIdentifier<Tables, TablesKey> locRibTableIID;
+    private BindingTransactionChain chain;
+    @GuardedBy("this")
+    private ListenerRegistration<LocRibWriter> reg;
+
+    private LocRibWriter(final RIBSupport<C,S,R,I> ribSupport,
+            final BindingTransactionChain chain,
+            final KeyedInstanceIdentifier<Rib, RibKey> ribIId,
+            final Long ourAs,
+            final DataBroker dataBroker,
+            final BGPRibRoutingPolicy ribPolicies,
+            final BGPPeerTracker peerTracker,
+            final TablesKey tablesKey,
+            final Class<? extends AfiSafiType> afiSafiType,
+            final PathSelectionMode pathSelectionMode) {
+        this.chain = requireNonNull(chain);
+        this.ribIId = requireNonNull(ribIId);
+        this.tk = requireNonNull(tablesKey);
+        this.locRibTableIID = ribIId.child(LocRib.class).child(Tables.class, this.tk);
+        this.ourAs = requireNonNull(ourAs);
+        this.dataBroker = requireNonNull(dataBroker);
+        this.ribSupport = requireNonNull(ribSupport);
+        this.peerTracker = peerTracker;
         this.pathSelectionMode = pathSelectionMode;
-        this.routeCounter = routeCounter;
 
-        final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
-        tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Routes.QNAME), this.ribSupport.emptyRoutes());
-        tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
-        tx.submit();
+        this.entryDep = new RouteEntryDependenciesContainerImpl(this.ribSupport, this.peerTracker, ribPolicies,
+                tablesKey, afiSafiType, this.locRibTableIID);
+        init();
+    }
 
-        final YangInstanceIdentifier tableId = target.node(Peer.QNAME).node(Peer.QNAME).node(EffectiveRibIn.QNAME).node(Tables.QNAME).node(tableKey);
-        final DOMDataTreeIdentifier wildcard = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId);
-        this.reg = service.registerDataTreeChangeListener(wildcard, this);
+    public static LocRibWriter create(
+            @Nonnull final RIBSupport ribSupport,
+            @Nonnull final TablesKey tablesKey,
+            @Nonnull final Class<? extends AfiSafiType> afiSafiType,
+            @Nonnull final BindingTransactionChain chain,
+            @Nonnull final KeyedInstanceIdentifier<Rib, RibKey> ribIId,
+            @Nonnull final AsNumber ourAs,
+            @Nonnull final DataBroker dataBroker,
+            final BGPRibRoutingPolicy ribPolicies,
+            @Nonnull final BGPPeerTracker peerTracker,
+            @Nonnull final PathSelectionMode pathSelectionStrategy) {
+        return new LocRibWriter(ribSupport, chain, ribIId, ourAs.getValue(), dataBroker, ribPolicies,
+                peerTracker, tablesKey, afiSafiType, pathSelectionStrategy);
     }
 
-    public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain,
-        @Nonnull final YangInstanceIdentifier target, @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final ExportPolicyPeerTracker ep,
-        @Nonnull final PathSelectionMode pathSelectionStrategy, @Nonnull final LongAdder routeCounter) {
-        return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, ep, tablesKey, pathSelectionStrategy, routeCounter);
+    private synchronized void init() {
+        final WriteTransaction tx = this.chain.newWriteOnlyTransaction();
+        tx.merge(LogicalDatastoreType.OPERATIONAL,
+                this.locRibTableIID.builder().child(Attributes.class).build(),
+                new AttributesBuilder().setUptodate(true).build());
+        tx.commit().addCallback(new FutureCallback<CommitInfo>() {
+            @Override
+            public void onSuccess(final CommitInfo result) {
+                LOG.trace("Successful commit");
+            }
+
+            @Override
+            public void onFailure(final Throwable trw) {
+                LOG.error("Failed commit", trw);
+            }
+        }, MoreExecutors.directExecutor());
+
+        final InstanceIdentifier<Tables> tableId = this.ribIId.builder().child(Peer.class)
+                .child(EffectiveRibIn.class).child(Tables.class, this.tk).build();
+        this.reg = this.dataBroker.registerDataTreeChangeListener(
+                new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, tableId), this);
+    }
+
+    /**
+     * Re-initialize this LocRibWriter with new transaction chain.
+     *
+     * @param newChain new transaction chain
+     */
+    synchronized void restart(@Nonnull final BindingTransactionChain newChain) {
+        requireNonNull(newChain);
+        close();
+        this.chain = newChain;
+        init();
     }
 
     @Override
-    public void close() {
-        this.reg.close();
-        // FIXME: wait for the chain to close? unfortunately RIBImpl is the listener, so that may require some work
-        this.chain.close();
+    public synchronized void close() {
+        if (this.reg != null) {
+            this.reg.close();
+            this.reg = null;
+        }
+        if (this.chain != null) {
+            this.chain.close();
+            this.chain = null;
+        }
     }
 
     @Nonnull
-    private RouteEntry createEntry(final PathArgument routeId) {
-        final RouteEntry ret = this.pathSelectionMode.createRouteEntry(ribSupport.isComplexRoute());
+    private RouteEntry<C,S,R,I> createEntry(final String routeId) {
+        final RouteEntry<C,S,R,I> ret = this.pathSelectionMode.createRouteEntry();
         this.routeEntries.put(routeId, ret);
+        this.totalPrefixesCounter.increment();
         LOG.trace("Created new entry for {}", routeId);
         return ret;
     }
@@ -127,12 +196,15 @@ final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeLis
      * @param changes on supported table
      */
     @Override
-    public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
+    public synchronized void onDataTreeChanged(final Collection<DataTreeModification<Tables>> changes) {
+        if (this.chain == null) {
+            LOG.trace("Chain closed, ignoring received data change {} to LocRib {}", changes, this);
+            return;
+        }
         LOG.trace("Received data change {} to LocRib {}", changes, this);
-
-        final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
+        final WriteTransaction tx = this.chain.newWriteOnlyTransaction();
         try {
-            final Map<RouteUpdateKey, RouteEntry> toUpdate = update(tx, changes);
+            final Map<RouteUpdateKey, RouteEntry<C,S,R,I>> toUpdate = update(tx, changes);
 
             if (!toUpdate.isEmpty()) {
                 walkThrough(tx, toUpdate.entrySet());
@@ -140,91 +212,189 @@ final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeLis
         } catch (final Exception e) {
             LOG.error("Failed to completely propagate updates {}, state is undefined", changes, e);
         } finally {
-            tx.submit();
+            tx.commit().addCallback(new FutureCallback<CommitInfo>() {
+                @Override
+                public void onSuccess(final CommitInfo result) {
+                    LOG.trace("Successful commit");
+                }
+
+                @Override
+                public void onFailure(final Throwable trw) {
+                    LOG.error("Failed commit", trw);
+                }
+            }, MoreExecutors.directExecutor());
         }
     }
 
-    private Map<RouteUpdateKey, RouteEntry> update(final DOMDataWriteTransaction tx, final Collection<DataTreeCandidate> changes) {
-        final Map<RouteUpdateKey, RouteEntry> ret = new HashMap<>();
-        changes.forEach(tc -> {
-            final DataTreeCandidateNode table = tc.getRootNode();
-            final YangInstanceIdentifier rootPath = tc.getRootPath();
-            final PeerId peerId = IdentifierUtils.peerKeyToPeerId(rootPath);
-            initializeTableWithExistentRoutes(table, peerId, rootPath, tx);
-            updateNodes(table, peerId, tx, ret);
-        });
+    @SuppressWarnings("unchecked")
+    private Map<RouteUpdateKey, RouteEntry<C, S, R, I>> update(final WriteTransaction tx,
+            final Collection<DataTreeModification<Tables>> changes) {
+        final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> ret = new HashMap<>();
+        for (final DataTreeModification<Tables> tc : changes) {
+            final DataObjectModification<Tables> table = tc.getRootNode();
+            final DataTreeIdentifier<Tables> rootPath = tc.getRootPath();
+            final KeyedInstanceIdentifier<Peer, PeerKey> peerKIid = (KeyedInstanceIdentifier<Peer, PeerKey>)
+                    rootPath.getRootIdentifier().firstIdentifierOf(Peer.class);
+            final UnsignedInteger peerUuid = RouterIds.routerIdForPeerId(peerKIid.getKey().getPeerId());
+            /*
+            Initialize Peer with routes under loc rib
+             */
+            if (!this.routeEntries.isEmpty() && table.getDataBefore() == null) {
+                final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer
+                        = this.peerTracker.getPeer(peerKIid.getKey().getPeerId());
+                if (toPeer != null && toPeer.supportsTable(this.entryDep.getLocalTablesKey())) {
+                    LOG.debug("Peer {} table has been created, inserting existent routes", toPeer.getPeerId());
+                    final List<ActualBestPathRoutes<C, S, R, I>> routesToStore = new ArrayList<>();
+                    for (final Map.Entry<String, RouteEntry<C, S, R, I>> entry : this.routeEntries.entrySet()) {
+                        final List<ActualBestPathRoutes<C, S, R, I>> filteredRoute = entry.getValue()
+                                .actualBestPaths(this.ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
+                        routesToStore.addAll(filteredRoute);
+                    }
+                    toPeer.initializeRibOut(this.entryDep, routesToStore);
+                }
+            }
+            /*
+            Process new routes from Peer
+             */
+            updateNodes(table, peerUuid, tx, ret);
+        }
         return ret;
     }
 
-    private void initializeTableWithExistentRoutes(final DataTreeCandidateNode table, final PeerId peerIdOfNewPeer, final YangInstanceIdentifier rootPath,
-        final DOMDataWriteTransaction tx) {
-        if (!table.getDataBefore().isPresent() && this.exportPolicyPeerTracker.isTableSupported(peerIdOfNewPeer)) {
-            LOG.debug("Peer {} table has been created, inserting existent routes", peerIdOfNewPeer);
-            final PeerRole newPeerRole = this.exportPolicyPeerTracker.getRole(IdentifierUtils.peerPath(rootPath));
-            final PeerExportGroup peerGroup = this.exportPolicyPeerTracker.getPeerGroup(newPeerRole);
-            this.routeEntries.entrySet().forEach(entry -> entry.getValue().writeRoute(peerIdOfNewPeer, entry.getKey(),
-                rootPath.getParent().getParent().getParent(), peerGroup, this.localTablesKey, this.exportPolicyPeerTracker, this.ribSupport, tx));
-        }
-    }
+    private void updateNodes(
+            final DataObjectModification<Tables> table,
+            final UnsignedInteger peerUuid,
+            final WriteTransaction tx,
+            final Map<RouteUpdateKey, RouteEntry<C,S,R,I>> routes
+    ) {
 
-    private void updateNodes(final DataTreeCandidateNode table, final PeerId peerId, final DOMDataWriteTransaction tx,
-        final Map<RouteUpdateKey, RouteEntry> routes) {
-        for (final DataTreeCandidateNode child : table.getChildNodes()) {
-            LOG.debug("Modification type {}", child.getModificationType());
-            if ((Attributes.QNAME).equals(child.getIdentifier().getNodeType())) {
-                if (child.getDataAfter().isPresent()) {
-                    // putting uptodate attribute in
-                    LOG.trace("Uptodate found for {}", child.getDataAfter());
-                    tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(child.getIdentifier()), child.getDataAfter().get());
-                }
-                continue;
+        final DataObjectModification<Attributes> attUpdate = table.getModifiedChildContainer(Attributes.class);
+
+        if (attUpdate != null) {
+            final Attributes newAttValue = attUpdate.getDataAfter();
+            if (newAttValue != null) {
+                LOG.trace("Uptodate found for {}", newAttValue);
+                tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTableIID.child(Attributes.class), newAttValue);
             }
-            updateRoutesEntries(child, peerId, routes);
         }
+
+        final DataObjectModification<S> routesChangesContainer
+                = table.getModifiedChildContainer(ribSupport.routesCaseClass(), ribSupport.routesContainerClass());
+        if (routesChangesContainer == null) {
+            return;
+        }
+        updateRoutesEntries(routesChangesContainer.getModifiedChildren(), peerUuid, routes);
     }
 
-    private void updateRoutesEntries(final DataTreeCandidateNode child, final PeerId peerId, final Map<RouteUpdateKey, RouteEntry> routes) {
-        final UnsignedInteger routerId = RouterIds.routerIdForPeerId(peerId);
-        final Collection<DataTreeCandidateNode> modifiedRoutes = this.ribSupport.changedRoutes(child);
-        for (final DataTreeCandidateNode route : modifiedRoutes) {
-            final PathArgument routeId = this.ribSupport.createRouteKeyPathArgument(route.getIdentifier());
-            RouteEntry entry = this.routeEntries.get(routeId);
-            final Optional<NormalizedNode<?, ?>> maybeData = route.getDataAfter();
-            final Optional<NormalizedNode<?, ?>> maybeDataBefore = route.getDataBefore();
-            if (maybeData.isPresent()) {
+    private void updateRoutesEntries(
+            final Collection<? extends DataObjectModification<? extends DataObject>> collection,
+            final UnsignedInteger routerId,
+            final Map<RouteUpdateKey, RouteEntry<C,S,R,I>> routes
+    ) {
+        for (final DataObjectModification<? extends DataObject> route : collection) {
+            final R newRoute = (R) route.getDataAfter();
+            final R oldRoute = (R) route.getDataBefore();
+            String routeKey;
+            RouteEntry<C,S,R,I> entry;
+            if (newRoute != null) {
+                routeKey = newRoute.getRouteKey();
+                entry = this.routeEntries.get(routeKey);
+
                 if (entry == null) {
-                    entry = createEntry(routeId);
+                    entry = createEntry(routeKey);
+                }
+
+                final long pathId = newRoute.getPathId().getValue();
+                entry.addRoute(routerId, pathId, newRoute);
+                this.totalPathsCounter.increment();
+            } else {
+                routeKey = oldRoute.getRouteKey();
+                entry = this.routeEntries.get(routeKey);
+                if(entry != null) {
+                    this.totalPathsCounter.decrement();
+                    final long pathId = oldRoute.getPathId().getValue();
+                    if (entry.removeRoute(routerId, pathId)) {
+                        this.routeEntries.remove(routeKey);
+                        this.totalPrefixesCounter.decrement();
+                        LOG.trace("Removed route from {}", routerId);
+                    }
                 }
-                entry.addRoute(routerId, this.ribSupport.extractPathId(maybeData.get()), this.attributesIdentifier, maybeData.get());
-            } else if (entry != null && entry.removeRoute(routerId, this.ribSupport.extractPathId(maybeDataBefore.get()))) {
-                this.routeEntries.remove(routeId);
-                LOG.trace("Removed route from {}", routerId);
             }
-            final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(peerId, routeId);
-            LOG.debug("Updated route {} entry {}", routeId, entry);
+            final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(routerId, routeKey);
+            LOG.debug("Updated route {} entry {}", routeKey, entry);
             routes.put(routeUpdateKey, entry);
         }
-        updateRouteCounter();
-    }
-
-    /**
-     * Update the statistic of loc-rib route
-     */
-    private void updateRouteCounter() {
-        this.routeCounter.reset();
-        this.routeCounter.add(this.routeEntries.size());
     }
 
-    private void walkThrough(final DOMDataWriteTransaction tx, final Set<Map.Entry<RouteUpdateKey, RouteEntry>> toUpdate) {
-        for (final Map.Entry<RouteUpdateKey, RouteEntry> e : toUpdate) {
+    private void walkThrough(final WriteTransaction tx,
+            final Set<Map.Entry<RouteUpdateKey, RouteEntry<C,S,R,I>>> toUpdate) {
+        final List<StaleBestPathRoute<C,S,R,I>> staleRoutes = new ArrayList<>();
+        final List<AdvertizedRoute<C,S,R,I>> newRoutes = new ArrayList<>();
+        for (final Map.Entry<RouteUpdateKey, RouteEntry<C,S,R,I>> e : toUpdate) {
             LOG.trace("Walking through {}", e);
-            final RouteEntry entry = e.getValue();
+            final RouteEntry<C,S,R,I> entry = e.getValue();
 
             if (!entry.selectBest(this.ourAs)) {
                 LOG.trace("Best path has not changed, continuing");
                 continue;
             }
-            entry.updateRoute(this.localTablesKey, this.exportPolicyPeerTracker, this.locRibTarget, this.ribSupport, tx, e.getKey().getRouteId());
+             entry.removeStalePaths(this.ribSupport, e.getKey().getRouteId()).ifPresent(staleRoutes::add);
+            newRoutes.addAll(entry.newBestPaths(this.ribSupport, e.getKey().getRouteId()));
+        }
+        updateLocRib(newRoutes, staleRoutes, tx);
+        this.peerTracker.getNonInternalPeers().parallelStream()
+                .forEach(toPeer->toPeer.refreshRibOut(this.entryDep, staleRoutes, newRoutes));
+    }
+
+    private void updateLocRib(final List<AdvertizedRoute<C, S, R, I>> newRoutes,
+            final List<StaleBestPathRoute<C, S, R, I>> staleRoutes,
+            final WriteTransaction tx) {
+        final KeyedInstanceIdentifier<Tables, TablesKey> locRibTarget = this.entryDep.getLocRibTableTarget();
+
+        for (final StaleBestPathRoute<C, S, R, I> staleContainer:staleRoutes) {
+            for (final I routeId: staleContainer.getStaleRouteKeyIdentifiers()) {
+                final InstanceIdentifier<R> routeTarget = ribSupport.createRouteIdentifier(locRibTarget, routeId);
+                LOG.debug("Delete route from LocRib {}", routeTarget);
+                tx.delete(LogicalDatastoreType.OPERATIONAL, routeTarget);
+            }
+        }
+
+        for (final AdvertizedRoute<C,S,R,I> advRoute : newRoutes) {
+            final R route = advRoute.getRoute();
+            final I iid = advRoute.getAddPathRouteKeyIdentifier();
+            final InstanceIdentifier<R> locRibRouteTarget
+                    = this.ribSupport.createRouteIdentifier(locRibTarget, iid);
+            LOG.debug("Write route to LocRib {}", route);
+            tx.put(LogicalDatastoreType.OPERATIONAL, locRibRouteTarget, route);
+        }
+    }
+
+    @Override
+    public long getPrefixesCount() {
+        return this.totalPrefixesCounter.longValue();
+    }
+
+    @Override
+    public long getPathsCount() {
+        return this.totalPathsCounter.longValue();
+    }
+
+    TablesKey getTableKey() {
+        return this.tk;
+    }
+
+    @Override
+    public synchronized void refreshTable(final TablesKey tk, final PeerId peerId) {
+        final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer = this.peerTracker.getPeer(peerId);
+        if (toPeer != null && toPeer.supportsTable(this.entryDep.getLocalTablesKey())) {
+            LOG.debug("Peer {} table has been created, inserting existent routes", toPeer.getPeerId());
+            final List<ActualBestPathRoutes<C, S, R, I>> routesToStore = new ArrayList<>();
+            for (final Map.Entry<String, RouteEntry<C, S, R, I>> entry : this.routeEntries.entrySet()) {
+                final List<ActualBestPathRoutes<C, S, R, I>> filteredRoute = entry.getValue()
+                        .actualBestPaths(this.ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
+                routesToStore.addAll(filteredRoute);
+            }
+            toPeer.reEvaluateAdvertizement(this.entryDep, routesToStore);
         }
     }
 }