Fix comparison between port numbers in match
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / services / SalFlowServiceImpl.java
index 0103234287a15c6258fe0ead47712582e4734562..5a4ed71f75fa31bd683ccf159873f79946e18a8a 100644 (file)
@@ -7,24 +7,33 @@
  */
 package org.opendaylight.openflowplugin.impl.services;
 
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
-import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
-import org.opendaylight.openflowplugin.api.openflow.device.Xid;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.SettableFuture;
-import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
-import com.google.common.base.Function;
 import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.JdkFutureAdapters;
 import com.google.common.util.concurrent.ListenableFuture;
-import java.math.BigInteger;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 import java.util.concurrent.Future;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.FlowConvertor;
+import javax.annotation.Nullable;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
+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;
+import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
+import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
+import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
+import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
+import org.opendaylight.openflowplugin.impl.util.ErrorUtil;
+import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
 import org.opendaylight.openflowplugin.openflow.md.util.FlowCreatorUtil;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
@@ -36,136 +45,222 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.Upda
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlow;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlow;
+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.openflow.protocol.rev130731.FlowModInputBuilder;
+import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-public class SalFlowServiceImpl extends CommonService implements SalFlowService {
+public class SalFlowServiceImpl implements SalFlowService, ItemLifeCycleSource {
+    private static final Logger LOG = LoggerFactory.getLogger(SalFlowServiceImpl.class);
+    private final FlowService<UpdateFlowOutput> flowUpdate;
+    private final FlowService<AddFlowOutput> flowAdd;
+    private final FlowService<RemoveFlowOutput> flowRemove;
+    private final DeviceContext deviceContext;
+    private ItemLifecycleListener itemLifecycleListener;
 
-    private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(SalFlowServiceImpl.class);
-
-
-    public SalFlowServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
-        super(requestContextStack, deviceContext);
+    public SalFlowServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext, final ConvertorExecutor convertorExecutor) {
+        this.deviceContext = deviceContext;
+        flowRemove = new FlowService<>(requestContextStack, deviceContext, RemoveFlowOutput.class, convertorExecutor);
+        flowAdd = new FlowService<>(requestContextStack, deviceContext, AddFlowOutput.class, convertorExecutor);
+        flowUpdate = new FlowService<>(requestContextStack, deviceContext, UpdateFlowOutput.class, convertorExecutor);
     }
 
-    <T, F> ListenableFuture<RpcResult<T>> handleServiceCall(final BigInteger connectionID,
-            final FlowModInputBuilder flowModInputBuilder, final Function<DataCrate<T>, Future<RpcResult<F>>> function) {
-        LOG.debug("Calling the FlowMod RPC method on MessageDispatchService");
-
-        final RequestContext<T> requestContext = requestContextStack.createRequestContext();
-        final SettableFuture<RpcResult<T>> result = requestContextStack.storeOrFail(requestContext);
-        final DataCrate<T> dataCrate = DataCrateBuilder.<T> builder().setiDConnection(connectionID)
-                .setRequestContext(requestContext).setFlowModInputBuilder(flowModInputBuilder).build();
-
-        if (!result.isDone()) {
-            final Future<RpcResult<F>> resultFromOFLib = function.apply(dataCrate);
-
-            final RpcResultConvertor<T> rpcResultConvertor = new RpcResultConvertor<>(requestContext, deviceContext);
-            rpcResultConvertor.processResultFromOfJava(resultFromOFLib);
-
-        } else {
-            RequestContextUtil.closeRequstContext(requestContext);
-        }
-        return result;
+    @Override
+    public void setItemLifecycleListener(@Nullable ItemLifecycleListener itemLifecycleListener) {
+        this.itemLifecycleListener = itemLifecycleListener;
     }
 
     @Override
     public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
-        final List<FlowModInputBuilder> ofFlowModInputs = FlowConvertor.toFlowModInputs(input, version, datapathId);
-        return processFlowModInputBuilders(ofFlowModInputs);
+        final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), input);
+        final ListenableFuture<RpcResult<AddFlowOutput>> future =
+                flowAdd.processFlowModInputBuilders(flowAdd.toFlowModInputs(input));
+        Futures.addCallback(future, new AddFlowCallback(input, flowRegistryKey));
+        return future;
     }
 
     @Override
     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
-
-        return this.<RemoveFlowOutput, Void> handleServiceCall(PRIMARY_CONNECTION,
-                new Function<DataCrate<RemoveFlowOutput>, Future<RpcResult<Void>>>() {
-                    @Override
-                    public Future<RpcResult<Void>> apply(final DataCrate<RemoveFlowOutput> data) {
-                        final FlowModInputBuilder ofFlowModInput = FlowConvertor.toFlowModInput(input, version,
-                                datapathId);
-                        return createResultForFlowMod(data, ofFlowModInput);
-                    }
-                });
+        final ListenableFuture<RpcResult<RemoveFlowOutput>> future =
+                flowRemove.processFlowModInputBuilders(flowRemove.toFlowModInputs(input));
+        Futures.addCallback(future, new RemoveFlowCallback(input));
+        return future;
     }
 
     @Override
     public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
-        final UpdateFlowInput in = input;
-        final UpdatedFlow updated = in.getUpdatedFlow();
-        final OriginalFlow original = in.getOriginalFlow();
+        final UpdatedFlow updated = input.getUpdatedFlow();
+        final OriginalFlow original = input.getOriginalFlow();
 
         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
-        List<FlowModInputBuilder> ofFlowModInputs;
+        final List<FlowModInputBuilder> ofFlowModInputs;
 
-        if (!FlowCreatorUtil.canModifyFlow(original, updated, version)) {
+        if (!FlowCreatorUtil.canModifyFlow(original, updated, flowUpdate.getVersion())) {
             // We would need to remove original and add updated.
 
             // remove flow
             final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
-            final List<FlowModInputBuilder> ofFlowRemoveInput = FlowConvertor.toFlowModInputs(removeflow.build(),
-                    version, datapathId);
+            final List<FlowModInputBuilder> ofFlowRemoveInput = flowUpdate.toFlowModInputs(removeflow.build());
             // remove flow should be the first
             allFlowMods.addAll(ofFlowRemoveInput);
             final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
-            ofFlowModInputs = FlowConvertor.toFlowModInputs(addFlowInputBuilder.build(), version, datapathId);
+            ofFlowModInputs = flowUpdate.toFlowModInputs(addFlowInputBuilder.build());
         } else {
-            ofFlowModInputs = FlowConvertor.toFlowModInputs(updated, version, datapathId);
+            ofFlowModInputs = flowUpdate.toFlowModInputs(updated);
         }
 
         allFlowMods.addAll(ofFlowModInputs);
-        return processFlowModInputBuilders(allFlowMods);
+        ListenableFuture<RpcResult<UpdateFlowOutput>> future = flowUpdate.processFlowModInputBuilders(allFlowMods);
+        Futures.addCallback(future, new UpdateFlowCallback(input));
+        return future;
+    }
+
+    @VisibleForTesting
+    private static KeyedInstanceIdentifier<Flow, FlowKey> createFlowPath(FlowDescriptor flowDescriptor,
+                                                                 KeyedInstanceIdentifier<Node, NodeKey> nodePath) {
+        return nodePath.augmentation(FlowCapableNode.class)
+                .child(Table.class, flowDescriptor.getTableKey())
+                .child(Flow.class, new FlowKey(flowDescriptor.getFlowId()));
     }
 
-    private <T> Future<RpcResult<T>> processFlowModInputBuilders(
-            final List<FlowModInputBuilder> ofFlowModInputs) {
-        final List<ListenableFuture<RpcResult<T>>> partialFutures = new ArrayList<>();
-        for (FlowModInputBuilder flowModInputBuilder : ofFlowModInputs) {
-            ListenableFuture<RpcResult<T>> partialFuture = handleServiceCall(PRIMARY_CONNECTION, flowModInputBuilder,
-                    new Function<DataCrate<T>, Future<RpcResult<Void>>>() {
-                        @Override
-                        public ListenableFuture<RpcResult<Void>> apply(final DataCrate<T> data) {
-                            return createResultForFlowMod(data);
-                        }
-                    });
-            partialFutures.add(partialFuture);
+    private class AddFlowCallback implements FutureCallback<RpcResult<AddFlowOutput>> {
+        private final AddFlowInput input;
+        private final FlowRegistryKey flowRegistryKey;
+
+        private AddFlowCallback(final AddFlowInput input,
+                                final FlowRegistryKey flowRegistryKey) {
+            this.input = input;
+            this.flowRegistryKey = flowRegistryKey;
         }
 
-        ListenableFuture<List<RpcResult<T>>> allFutures = Futures.allAsList(partialFutures);
-        final SettableFuture<RpcResult<T>> finalFuture = SettableFuture.create();
-        Futures.addCallback(allFutures, new FutureCallback<List<RpcResult<T>>>() {
-            @Override
-            public void onSuccess(List<RpcResult<T>> result) {
-                for (RpcResult<T> rpcResult : result) {
-                    if (rpcResult.isSuccessful()) {
-                        // TODO: AddFlowOutput has getTransactionId() - shouldn't it have some value?
-                        finalFuture.set(RpcResultBuilder.<T> success().build());
-                    }
+        @Override
+        public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
+            if (rpcResult.isSuccessful()) {
+                final FlowDescriptor flowDescriptor;
+
+                if (Objects.nonNull(input.getFlowRef())) {
+                    final FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
+                    flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
+                    deviceContext.getDeviceFlowRegistry().store(flowRegistryKey, flowDescriptor);
+                } else {
+                    final FlowId flowId = deviceContext.getDeviceFlowRegistry().storeIfNecessary(flowRegistryKey);
+                    flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
                 }
-            }
 
-            @Override
-            public void onFailure(Throwable t) {
-                finalFuture.set(RpcResultBuilder.<T> failed().withError(ErrorType.APPLICATION, "", t.getMessage())
-                        .build());
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Flow add with id={} finished without error", flowDescriptor.getFlowId().getValue());
+                }
+
+                if (itemLifecycleListener != null) {
+                    KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
+                            deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
+                    final FlowBuilder flowBuilder = new FlowBuilder(input).setId(flowDescriptor.getFlowId());
+                    itemLifecycleListener.onAdded(flowPath, flowBuilder.build());
+                }
+            } else {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Flow add failed for flow={}, errors={}", input,
+                            ErrorUtil.errorsToString(rpcResult.getErrors()));
+                }
             }
-        });
+        }
 
-        return finalFuture;
+        @Override
+        public void onFailure(final Throwable throwable) {
+            LOG.warn("Service call for adding flow={} failed, reason: {}", input, throwable);
+        }
     }
 
-    protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final DataCrate<T> data) {
-        return createResultForFlowMod(data, data.getFlowModInputBuilder()) ;
-    }
+    private class RemoveFlowCallback implements FutureCallback<RpcResult<RemoveFlowOutput>> {
+        private final RemoveFlowInput input;
+
+        private RemoveFlowCallback(final RemoveFlowInput input) {
+            this.input = input;
+        }
+
+        @Override
+        public void onSuccess(final RpcResult<RemoveFlowOutput> result) {
+            if (result.isSuccessful()) {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Flow remove finished without error for flow={}", input);
+                }
+                FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), input);
+                deviceContext.getDeviceFlowRegistry().removeDescriptor(flowRegistryKey);
+
+                if (itemLifecycleListener != null) {
+                    final FlowDescriptor flowDescriptor =
+                            deviceContext.getDeviceFlowRegistry().retrieveIdForFlow(flowRegistryKey);
+                    if (flowDescriptor != null) {
+                        KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
+                                deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
+                        itemLifecycleListener.onRemoved(flowPath);
+                    }
+                }
+            } else {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Flow remove failed for flow={}, errors={}", input,
+                            ErrorUtil.errorsToString(result.getErrors()));
+                }
+            }
+        }
 
-    protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final DataCrate<T> data, final FlowModInputBuilder flowModInput) {
-        final Xid xId = deviceContext.getNextXid();
-        flowModInput.setXid(xId.getValue());
-        data.getRequestContext().setXid(xId);
-        Future<RpcResult<Void>> flowModResult = provideConnectionAdapter(data.getiDConnection()).flowMod(
-                flowModInput.build());
-        return JdkFutureAdapters.listenInPoolThread(flowModResult);
+        @Override
+        public void onFailure(final Throwable throwable) {
+            LOG.warn("Service call for removing flow={} failed, reason: {}", input, throwable);
+        }
     }
 
+    private class UpdateFlowCallback implements FutureCallback<RpcResult<UpdateFlowOutput>> {
+        private final UpdateFlowInput input;
+
+        private UpdateFlowCallback(UpdateFlowInput input) {
+            this.input = input;
+        }
+
+        @Override
+        public void onSuccess(final RpcResult<UpdateFlowOutput> o) {
+            final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
+
+            final UpdatedFlow updated = input.getUpdatedFlow();
+            final OriginalFlow original = input.getOriginalFlow();
+            final FlowRegistryKey origFlowRegistryKey = FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), original);
+            final FlowRegistryKey updatedFlowRegistryKey = FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), updated);
+            final FlowDescriptor origFlowDescriptor = deviceFlowRegistry.retrieveIdForFlow(origFlowRegistryKey);
+
+            final boolean isUpdate = Objects.nonNull(origFlowDescriptor);
+            final FlowId fLowId = Objects.nonNull(input.getFlowRef())
+                    ? input.getFlowRef().getValue().firstKeyOf(Flow.class).getId()
+                    : isUpdate ? origFlowDescriptor.getFlowId() : deviceFlowRegistry.storeIfNecessary(updatedFlowRegistryKey);
+            final FlowDescriptor updatedFlowDescriptor = FlowDescriptorFactory.create(updated.getTableId(), fLowId);
+            if (isUpdate) {
+                deviceFlowRegistry.removeDescriptor(origFlowRegistryKey);
+                deviceFlowRegistry.store(updatedFlowRegistryKey, updatedFlowDescriptor);
+            }
+
+            if (itemLifecycleListener != null) {
+                final KeyedInstanceIdentifier<Flow, FlowKey> flowPath =
+                        createFlowPath(
+                                updatedFlowDescriptor,
+                                deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
+
+                final Flow flow = new FlowBuilder(updated)
+                        .setId(updatedFlowDescriptor.getFlowId())
+                        .build();
+
+                if (Objects.nonNull(origFlowDescriptor)) {
+                    itemLifecycleListener.onUpdated(flowPath, flow);
+                } else {
+                    itemLifecycleListener.onAdded(flowPath, flow);
+                }
+            }
+        }
+
+        @Override
+        public void onFailure(final Throwable throwable) {
+            LOG.warn("Service call for updating flow={} failed, reason: {}", input, throwable);
+        }
+    }
 }