Fix an eclipse nullness warning
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / LocRibWriter.java
index 6e854a7695f2b3e9e8db575f5d7c2f78cf0e646d..5e03801026c463677e885be523ace22a1951405b 100644 (file)
@@ -10,8 +10,12 @@ package org.opendaylight.protocol.bgp.rib.impl;
 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;
@@ -26,15 +30,22 @@ 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.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.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.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.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;
@@ -46,22 +57,29 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.
 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.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, TotalPrefixesCounter, TotalPathsCounter,
+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 final Map<String, RouteEntry> routeEntries = new HashMap<>();
+    private final Map<String, RouteEntry<C,S,R,I>> routeEntries = new HashMap<>();
     private final Long ourAs;
-    private final RIBSupport ribSupport;
+    private final RIBSupport<C,S,R,I> ribSupport;
     private final DataBroker dataBroker;
     private final PathSelectionMode pathSelectionMode;
     private final LongAdder totalPathsCounter = new LongAdder();
@@ -75,7 +93,7 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
     @GuardedBy("this")
     private ListenerRegistration<LocRibWriter> reg;
 
-    private LocRibWriter(final RIBSupport ribSupport,
+    private LocRibWriter(final RIBSupport<C,S,R,I> ribSupport,
             final BindingTransactionChain chain,
             final KeyedInstanceIdentifier<Rib, RibKey> ribIId,
             final Long ourAs,
@@ -83,6 +101,7 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
             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);
@@ -94,13 +113,15 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
         this.peerTracker = peerTracker;
         this.pathSelectionMode = pathSelectionMode;
 
-        this.entryDep = new RouteEntryDependenciesContainerImpl(this.ribSupport, ribPolicies,
-                tablesKey, this.locRibTableIID);
+        this.entryDep = new RouteEntryDependenciesContainerImpl(this.ribSupport, this.peerTracker, ribPolicies,
+                tablesKey, afiSafiType, this.locRibTableIID);
         init();
     }
 
-    public static LocRibWriter create(@Nonnull final RIBSupport ribSupport,
+    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,
@@ -109,21 +130,30 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
             @Nonnull final BGPPeerTracker peerTracker,
             @Nonnull final PathSelectionMode pathSelectionStrategy) {
         return new LocRibWriter(ribSupport, chain, ribIId, ourAs.getValue(), dataBroker, ribPolicies,
-                peerTracker, tablesKey, pathSelectionStrategy);
+                peerTracker, tablesKey, afiSafiType, pathSelectionStrategy);
     }
 
-    @SuppressWarnings("unchecked")
     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.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());
 
         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);
+                new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, tableId), this);
     }
 
     /**
@@ -151,8 +181,8 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
     }
 
     @Nonnull
-    private RouteEntry createEntry(final String routeId) {
-        final RouteEntry ret = this.pathSelectionMode.createRouteEntry();
+    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);
@@ -174,7 +204,7 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
         LOG.trace("Received data change {} to LocRib {}", changes, this);
         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());
@@ -182,14 +212,24 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
         } 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());
         }
     }
 
     @SuppressWarnings("unchecked")
-    private Map<RouteUpdateKey, RouteEntry> update(final WriteTransaction tx,
+    private Map<RouteUpdateKey, RouteEntry<C, S, R, I>> update(final WriteTransaction tx,
             final Collection<DataTreeModification<Tables>> changes) {
-        final Map<RouteUpdateKey, RouteEntry> ret = new HashMap<>();
+        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();
@@ -200,12 +240,17 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
             Initialize Peer with routes under loc rib
              */
             if (!this.routeEntries.isEmpty() && table.getDataBefore() == null) {
-                final org.opendaylight.protocol.bgp.rib.spi.Peer peer
+                final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer
                         = this.peerTracker.getPeer(peerKIid.getKey().getPeerId());
-                if (peer != null && peer.supportsTable(this.entryDep.getLocalTablesKey())) {
-                    LOG.debug("Peer {} table has been created, inserting existent routes", peer.getPeerId());
-                    this.routeEntries.forEach((key, value) -> value.initializeBestPaths(this.entryDep,
-                            new RouteEntryInfoImpl(peer, key), tx));
+                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);
                 }
             }
             /*
@@ -216,41 +261,41 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
         return ret;
     }
 
-    @SuppressWarnings("unchecked")
     private void updateNodes(
             final DataObjectModification<Tables> table,
             final UnsignedInteger peerUuid,
             final WriteTransaction tx,
-            final Map<RouteUpdateKey, RouteEntry> routes
+            final Map<RouteUpdateKey, RouteEntry<C,S,R,I>> routes
     ) {
 
         final DataObjectModification<Attributes> attUpdate = table.getModifiedChildContainer(Attributes.class);
 
-        if (attUpdate != null && attUpdate.getDataAfter() != null) {
+        if (attUpdate != null) {
             final Attributes newAttValue = attUpdate.getDataAfter();
-            LOG.trace("Uptodate found for {}", newAttValue);
-            tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTableIID.child(Attributes.class), newAttValue);
+            if (newAttValue != null) {
+                LOG.trace("Uptodate found for {}", newAttValue);
+                tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTableIID.child(Attributes.class), newAttValue);
+            }
         }
 
-        final DataObjectModification routesChangesContainer =
-                table.getModifiedChildContainer(this.ribSupport.routesContainerClass());
+        final DataObjectModification<S> routesChangesContainer
+                = table.getModifiedChildContainer(ribSupport.routesCaseClass(), ribSupport.routesContainerClass());
         if (routesChangesContainer == null) {
             return;
         }
         updateRoutesEntries(routesChangesContainer.getModifiedChildren(), peerUuid, routes);
     }
 
-    @SuppressWarnings("unchecked")
     private void updateRoutesEntries(
-            final Collection<DataObjectModification<? extends DataObject>> routeChanges,
+            final Collection<? extends DataObjectModification<? extends DataObject>> collection,
             final UnsignedInteger routerId,
-            final Map<RouteUpdateKey, RouteEntry> routes
+            final Map<RouteUpdateKey, RouteEntry<C,S,R,I>> routes
     ) {
-        for (final DataObjectModification<? extends DataObject> route : routeChanges) {
-            final Route newRoute = (Route) route.getDataAfter();
-            final Route oldRoute = (Route) route.getDataBefore();
+        for (final DataObjectModification<? extends DataObject> route : collection) {
+            final R newRoute = (R) route.getDataAfter();
+            final R oldRoute = (R) route.getDataBefore();
             String routeKey;
-            RouteEntry entry;
+            RouteEntry<C,S,R,I> entry;
             if (newRoute != null) {
                 routeKey = newRoute.getRouteKey();
                 entry = this.routeEntries.get(routeKey);
@@ -282,16 +327,45 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
     }
 
     private void walkThrough(final WriteTransaction tx,
-            final Set<Map.Entry<RouteUpdateKey, RouteEntry>> toUpdate) {
-        for (final Map.Entry<RouteUpdateKey, RouteEntry> e : toUpdate) {
+            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.updateBestPaths(entryDep, e.getKey().getRouteId(), tx);
+             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);
         }
     }
 
@@ -305,7 +379,22 @@ final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPa
         return this.totalPathsCounter.longValue();
     }
 
-    public TablesKey getTableKey() {
+    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);
+        }
+    }
 }