Simplify CommonService interface
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / services / SalFlowServiceImpl.java
index 9efcdf12ecb47623c6a1c50f7dafba90a86063d5..515acd918631ded9aafc0d3a1b53fa398ccb50f2 100644 (file)
@@ -7,23 +7,21 @@
  */
 package org.opendaylight.openflowplugin.impl.services;
 
-import com.google.common.base.Function;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.JdkFutureAdapters;
 import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import java.math.BigInteger;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.List;
 import java.util.concurrent.Future;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
-import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
-import org.opendaylight.openflowplugin.api.openflow.device.Xid;
-import org.opendaylight.openflowplugin.api.openflow.flow.registry.FlowHash;
-import org.opendaylight.openflowplugin.impl.flow.registry.FlowHashFactory;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.FlowConvertor;
+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.impl.registry.flow.FlowDescriptorFactory;
+import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
+import org.opendaylight.openflowplugin.impl.util.FlowUtil;
 import org.opendaylight.openflowplugin.openflow.md.util.FlowCreatorUtil;
 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.Flow;
@@ -40,86 +38,89 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.Upda
 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.openflow.protocol.rev130731.FlowModInputBuilder;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
+import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-public class SalFlowServiceImpl extends CommonService implements SalFlowService {
-
-    private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(SalFlowServiceImpl.class);
+public class SalFlowServiceImpl implements SalFlowService {
+    private static final Logger LOG = LoggerFactory.getLogger(SalFlowServiceImpl.class);
+    private final FlowService<UpdateFlowOutput> flowUpdate;
+    private final FlowService<AddFlowOutput> flowAdd;
+    private final FlowRemoveService flowRemove;
 
     public SalFlowServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
-        super(requestContextStack, deviceContext);
+        flowRemove = new FlowRemoveService(requestContextStack, deviceContext);
+        flowAdd = new FlowService<>(requestContextStack, deviceContext, AddFlowOutput.class);
+        flowUpdate = new FlowService<>(requestContextStack, deviceContext, UpdateFlowOutput.class);
     }
 
-    <T, F> ListenableFuture<RpcResult<T>> handleServiceCall(final BigInteger connectionID,
-                                                            final FlowModInputBuilder flowModInputBuilder, final Function<DataCrate<T>, ListenableFuture<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 ListenableFuture<RpcResult<F>> resultFromOFLib = function.apply(dataCrate);
-
-            final OFJResult2RequestCtxFuture<T> OFJResult2RequestCtxFuture = new OFJResult2RequestCtxFuture<>(requestContext, deviceContext);
-            OFJResult2RequestCtxFuture.processResultFromOfJava(resultFromOFLib);
-
+    @Override
+    public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
+        final ListenableFuture<RpcResult<AddFlowOutput>> future = flowAdd.processFlowModInputBuilders(flowAdd.toFlowModInputs(input));
+        final FlowId flowId;
+        if (null != input.getFlowRef()) {
+            flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
         } else {
-            RequestContextUtil.closeRequstContext(requestContext);
+            flowId = FlowUtil.createAlienFlowId(input.getTableId());
         }
-        return result;
-    }
 
-    @Override
-    public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
-        final List<FlowModInputBuilder> ofFlowModInputs = FlowConvertor.toFlowModInputs(input, version, datapathId);
-        final ListenableFuture future = processFlowModInputBuilders(ofFlowModInputs);
-        Futures.addCallback(future, new FutureCallback() {
+        final DeviceContext deviceContext = flowAdd.getDeviceContext();
+        final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(input);
+        final FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
+        deviceContext.getDeviceFlowRegistry().store(flowRegistryKey, flowDescriptor);
+        Futures.addCallback(future, new FutureCallback<RpcResult<AddFlowOutput>>() {
             @Override
-            public void onSuccess(final Object o) {
-                FlowHash flowHash = FlowHashFactory.create(input);
-                FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
-                deviceContext.getFlowRegistry().store(flowHash, flowId);
+            public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
+                if (rpcResult.isSuccessful()) {
+                    LOG.debug("flow add finished without error, id={}", flowId.getValue());
+                } else {
+                    LOG.debug("flow add failed with error, id={}", flowId.getValue());
+                }
             }
 
             @Override
             public void onFailure(final Throwable throwable) {
-                LOG.trace("Service call for adding flows failed.", throwable);
-                LOG.trace("Future is canceld : {}.", future.isCancelled());
+                deviceContext.getDeviceFlowRegistry().markToBeremoved(flowRegistryKey);
+                LOG.trace("Service call for adding flows failed, id={}.", flowId.getValue(), throwable);
             }
         });
+
         return future;
     }
 
     @Override
     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
+        LOG.trace("Calling remove flow for flow with ID ={}.", input.getFlowRef());
 
-        return this.<RemoveFlowOutput, Void>handleServiceCall(PRIMARY_CONNECTION,
-                new Function<DataCrate<RemoveFlowOutput>, ListenableFuture<RpcResult<Void>>>() {
-                    @Override
-                    public ListenableFuture<RpcResult<Void>> apply(final DataCrate<RemoveFlowOutput> data) {
-                        final FlowModInputBuilder ofFlowModInput = FlowConvertor.toFlowModInput(input, version,
-                                datapathId);
-                        ListenableFuture future = createResultForFlowMod(data, ofFlowModInput);
-                        Futures.addCallback(future, new FutureCallback() {
-                            @Override
-                            public void onSuccess(final Object o) {
-                                FlowHash flowHash = FlowHashFactory.create(input);
-                                deviceContext.getFlowRegistry().remove(flowHash);
-                            }
-
-                            @Override
-                            public void onFailure(final Throwable throwable) {
-                                //NOOP
+        final ListenableFuture<RpcResult<RemoveFlowOutput>> future = flowRemove.handleServiceCall(input);
+        Futures.addCallback(future, new FutureCallback<RpcResult<RemoveFlowOutput>>() {
+            @Override
+            public void onSuccess(final RpcResult<RemoveFlowOutput> result) {
+                if (result.isSuccessful()) {
+                    FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(input);
+                    flowRemove.getDeviceContext().getDeviceFlowRegistry().markToBeremoved(flowRegistryKey);
+                } else {
+                    if (LOG.isTraceEnabled()) {
+                        StringBuilder errors = new StringBuilder();
+                        Collection<RpcError> rpcErrors = result.getErrors();
+                        if (null != rpcErrors && rpcErrors.size() > 0) {
+                            for (RpcError rpcError : rpcErrors) {
+                                errors.append(rpcError.getMessage());
                             }
-                        });
-                        return future;
+                        }
+                        LOG.trace("Flow modification failed. Errors : {}", errors.toString());
                     }
-                });
+                }
+            }
+
+            @Override
+            public void onFailure(final Throwable throwable) {
+                LOG.trace("Flow modification failed..", throwable);
+            }
+        });
+
+        return future;
     }
 
     @Override
@@ -129,93 +130,42 @@ public class SalFlowServiceImpl extends CommonService implements SalFlowService
         final OriginalFlow original = in.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);
-        ListenableFuture future = processFlowModInputBuilders(allFlowMods);
-        Futures.addCallback(future, new FutureCallback() {
+        ListenableFuture<RpcResult<UpdateFlowOutput>> future = flowUpdate.processFlowModInputBuilders(allFlowMods);
+        Futures.addCallback(future, new FutureCallback<RpcResult<UpdateFlowOutput>>() {
             @Override
-            public void onSuccess(final Object o) {
-                FlowHash flowHash = FlowHashFactory.create(original);
-                deviceContext.getFlowRegistry().remove(flowHash);
+            public void onSuccess(final RpcResult<UpdateFlowOutput> o) {
+                FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(original);
 
-                flowHash = FlowHashFactory.create(updated);
+                FlowRegistryKey updatedflowRegistryKey = FlowRegistryKeyFactory.create(updated);
                 FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
-                deviceContext.getFlowRegistry().store(flowHash, flowId);
-
+                FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(updated.getTableId(), flowId);
+                final DeviceFlowRegistry deviceFlowRegistry = flowUpdate.getDeviceContext().getDeviceFlowRegistry();
+                deviceFlowRegistry.markToBeremoved(flowRegistryKey);
+                deviceFlowRegistry.store(updatedflowRegistryKey, flowDescriptor);
             }
 
             @Override
             public void onFailure(final Throwable throwable) {
-
+                LOG.debug("Flow update failed", throwable);
             }
         });
         return future;
     }
-
-    private <T> ListenableFuture<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>, ListenableFuture<RpcResult<Void>>>() {
-                        @Override
-                        public ListenableFuture<RpcResult<Void>> apply(final DataCrate<T> data) {
-                            return createResultForFlowMod(data);
-                        }
-                    });
-            partialFutures.add(partialFuture);
-        }
-
-        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 onFailure(Throwable t) {
-                finalFuture.set(RpcResultBuilder.<T>failed().withError(ErrorType.APPLICATION, "", t.getMessage())
-                        .build());
-            }
-        });
-
-        return finalFuture;
-    }
-
-    protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final DataCrate<T> data) {
-        return createResultForFlowMod(data, data.getFlowModInputBuilder());
-    }
-
-    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);
-    }
-
 }