Switch to MD-SAL APIs
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / registry / flow / DeviceFlowRegistryImpl.java
index bb53d3b5708096f198087cc34e66a07933dbd924..1e2818ac4d4e10631c68bd763100c0409e74feed 100644 (file)
@@ -8,28 +8,30 @@
 package org.opendaylight.openflowplugin.impl.registry.flow;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
 import com.google.common.collect.BiMap;
 import com.google.common.collect.HashBiMap;
 import com.google.common.collect.Maps;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FluentFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.Optional;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Consumer;
 import javax.annotation.Nonnull;
 import javax.annotation.concurrent.ThreadSafe;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.mdsal.binding.api.DataBroker;
+import org.opendaylight.mdsal.binding.api.ReadTransaction;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
+import org.opendaylight.mdsal.common.api.ReadFailedException;
 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
@@ -38,6 +40,8 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.Fl
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNodesNodeTableFlow;
+import org.opendaylight.yangtools.util.concurrent.FluentFutures;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
 import org.slf4j.Logger;
@@ -65,7 +69,7 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
         flowConsumer = flow -> {
             final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(version, flow);
 
-            if (!flowRegistry.containsKey(flowRegistryKey)) {
+            if (getExistingKey(flowRegistryKey) == null) {
                 // Now, we will update the registry
                 storeDescriptor(flowRegistryKey, FlowDescriptorFactory.create(flow.getTableId(), flow.getId()));
             }
@@ -83,13 +87,13 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
         final InstanceIdentifier<FlowCapableNode> path = instanceIdentifier.augmentation(FlowCapableNode.class);
 
         // First, try to fill registry with flows from DS/Configuration
-        final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> configFuture =
+        final FluentFuture<Optional<FlowCapableNode>> configFuture =
                 fillFromDatastore(LogicalDatastoreType.CONFIGURATION, path);
 
         // Now, try to fill registry with flows from DS/Operational
         // in case of cluster fail over, when clients are not using DS/Configuration
         // for adding flows, but only RPCs
-        final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> operationalFuture =
+        final FluentFuture<Optional<FlowCapableNode>> operationalFuture =
                 fillFromDatastore(LogicalDatastoreType.OPERATIONAL, path);
 
         // And at last, chain and return futures created above.
@@ -101,32 +105,30 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
         return lastFillFuture;
     }
 
-    private CheckedFuture<Optional<FlowCapableNode>, ReadFailedException>
-            fillFromDatastore(final LogicalDatastoreType logicalDatastoreType,
+    private FluentFuture<Optional<FlowCapableNode>> fillFromDatastore(final LogicalDatastoreType logicalDatastoreType,
                               final InstanceIdentifier<FlowCapableNode> path) {
         // Create new read-only transaction
-        final ReadOnlyTransaction transaction = dataBroker.newReadOnlyTransaction();
+        final ReadTransaction transaction = dataBroker.newReadOnlyTransaction();
 
         // Bail out early if transaction is null
         if (transaction == null) {
-            return Futures.immediateFailedCheckedFuture(
+            return FluentFutures.immediateFailedFluentFuture(
                     new ReadFailedException("Read transaction is null"));
         }
 
         // Prepare read operation from datastore for path
-        final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> future =
-                transaction.read(logicalDatastoreType, path);
+        final FluentFuture<Optional<FlowCapableNode>> future = transaction.read(logicalDatastoreType, path);
 
         // Bail out early if future is null
         if (future == null) {
-            return Futures.immediateFailedCheckedFuture(
+            return FluentFutures.immediateFailedFluentFuture(
                     new ReadFailedException("Future from read transaction is null"));
         }
 
-        Futures.addCallback(future, new FutureCallback<Optional<FlowCapableNode>>() {
+        future.addCallback(new FutureCallback<Optional<FlowCapableNode>>() {
             @Override
-            public void onSuccess(Optional<FlowCapableNode> result) {
-                result.asSet().stream()
+            public void onSuccess(@Nonnull Optional<FlowCapableNode> result) {
+                result.map(Collections::singleton).orElse(Collections.emptySet()).stream()
                         .filter(Objects::nonNull)
                         .filter(flowCapableNode -> Objects.nonNull(flowCapableNode.getTable()))
                         .flatMap(flowCapableNode -> flowCapableNode.getTable().stream())
@@ -146,7 +148,7 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
                 // Even when read operation failed, close the transaction
                 transaction.close();
             }
-        });
+        }, MoreExecutors.directExecutor());
 
         return future;
     }
@@ -154,10 +156,14 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
     @Override
     public FlowDescriptor retrieveDescriptor(@Nonnull final FlowRegistryKey flowRegistryKey) {
         if (LOG.isTraceEnabled()) {
-            LOG.trace("Retrieving flow descriptor for flow hash : {}", flowRegistryKey.hashCode());
+            LOG.trace("Retrieving flow descriptor for flow registry : {}", flowRegistryKey.toString());
         }
 
-        return flowRegistry.get(flowRegistryKey);
+        FlowRegistryKey existingFlowRegistryKey = getExistingKey(flowRegistryKey);
+        if (existingFlowRegistryKey != null) {
+            return flowRegistry.get(existingFlowRegistryKey);
+        }
+        return null;
     }
 
     @Override
@@ -168,10 +174,10 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
                 LOG.trace("Storing flowDescriptor with table ID : {} and flow ID : {} for flow hash : {}",
                         flowDescriptor.getTableKey().getId(),
                         flowDescriptor.getFlowId().getValue(),
-                        flowRegistryKey.hashCode());
+                        flowRegistryKey.toString());
             }
 
-            flowRegistry.put(flowRegistryKey, flowDescriptor);
+            addToFlowRegistry(flowRegistryKey, flowDescriptor);
         } catch (IllegalArgumentException ex) {
             if (LOG.isWarnEnabled()) {
                 LOG.warn("Flow with flow ID {} already exists in table {}, generating alien flow ID",
@@ -181,7 +187,7 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
 
             // We are trying to store new flow to flow registry, but we already have different flow with same flow ID
             // stored in registry, so we need to create alien ID for this new flow here.
-            flowRegistry.put(
+            addToFlowRegistry(
                     flowRegistryKey,
                     FlowDescriptorFactory.create(
                             flowDescriptor.getTableKey().getId(),
@@ -194,7 +200,7 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
         if (Objects.isNull(retrieveDescriptor(flowRegistryKey))) {
             if (LOG.isDebugEnabled()) {
                 LOG.debug("Flow descriptor for flow hash : {} not found, generating alien flow ID",
-                        flowRegistryKey.hashCode());
+                        flowRegistryKey.toString());
             }
 
             // We do not found flow in flow registry, that means it do not have any ID already assigned, so we need
@@ -210,10 +216,10 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
     @Override
     public void addMark(final FlowRegistryKey flowRegistryKey) {
         if (LOG.isTraceEnabled()) {
-            LOG.trace("Removing flow descriptor for flow hash : {}", flowRegistryKey.hashCode());
+            LOG.trace("Removing flow descriptor for flow hash : {}", flowRegistryKey.toString());
         }
 
-        flowRegistry.remove(flowRegistryKey);
+        removeFromFlowRegistry(flowRegistryKey);
     }
 
     @Override
@@ -255,6 +261,46 @@ public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
         return new FlowId(alienId);
     }
 
+    //Hashcode generation of the extension augmentation can differ for the same object received from the datastore and
+    // the one received after deserialization of switch message. OpenFlowplugin extensions are list, and the order in
+    // which it can receive the extensions back from switch can differ and that lead to a different hashcode. In that
+    // scenario, hashcode won't match and flowRegistry return the  related key. To overcome this issue, these methods
+    // make sure that key is stored only if it doesn't equals to any existing key.
+    private void addToFlowRegistry(final FlowRegistryKey flowRegistryKey, final FlowDescriptor flowDescriptor) {
+        FlowRegistryKey existingFlowRegistryKey = getExistingKey(flowRegistryKey);
+        if (existingFlowRegistryKey == null) {
+            flowRegistry.put(flowRegistryKey, flowDescriptor);
+        } else {
+            flowRegistry.put(existingFlowRegistryKey, flowDescriptor);
+        }
+    }
+
+    private void removeFromFlowRegistry(final FlowRegistryKey flowRegistryKey) {
+        FlowRegistryKey existingFlowRegistryKey = getExistingKey(flowRegistryKey);
+        if (existingFlowRegistryKey != null) {
+            flowRegistry.remove(existingFlowRegistryKey);
+        } else {
+            flowRegistry.remove(flowRegistryKey);
+        }
+    }
+
+    private FlowRegistryKey getExistingKey(final FlowRegistryKey flowRegistryKey) {
+        if (flowRegistryKey.getMatch().augmentation(GeneralAugMatchNodesNodeTableFlow.class) == null) {
+            if (flowRegistry.containsKey(flowRegistryKey)) {
+                return flowRegistryKey;
+            }
+        } else {
+            synchronized (flowRegistry) {
+                for (Map.Entry<FlowRegistryKey, FlowDescriptor> keyValueSet : flowRegistry.entrySet()) {
+                    if (keyValueSet.getKey().equals(flowRegistryKey)) {
+                        return keyValueSet.getKey();
+                    }
+                }
+            }
+        }
+        return null;
+    }
+
     @VisibleForTesting
     Map<FlowRegistryKey, FlowDescriptor> getAllFlowDescriptors() {
         return flowRegistry;