device context provides attached any messege type listener
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceContextImpl.java
index da2193c1a38d15b701f501a052c6d82d5566c03a..c797107668ad8da38124507f27e8861a17cad4c8 100644 (file)
@@ -10,10 +10,16 @@ package org.opendaylight.openflowplugin.impl.device;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.SettableFuture;
+import io.netty.util.HashedWheelTimer;
+import io.netty.util.Timeout;
+import io.netty.util.TimerTask;
 import java.math.BigInteger;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.TreeMap;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicLong;
 import javax.annotation.Nonnull;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
@@ -21,21 +27,21 @@ import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceReplyProcessor;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
 import org.opendaylight.openflowplugin.api.openflow.device.exception.DeviceDataException;
+import org.opendaylight.openflowplugin.api.openflow.device.listener.AnyMessageTypeListener;
 import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
-import org.opendaylight.openflowplugin.impl.device.translator.PacketReceivedTranslator;
-import org.opendaylight.openflowplugin.impl.device.translator.PortUpdateTranslator;
+import org.opendaylight.openflowplugin.impl.translator.PacketReceivedTranslator;
 import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
@@ -53,7 +59,7 @@ import org.slf4j.LoggerFactory;
 /**
  *
  */
-public class DeviceContextImpl implements DeviceContext, DeviceReplyProcessor {
+public class DeviceContextImpl implements DeviceContext {
 
     private static final Logger LOG = LoggerFactory.getLogger(DeviceContextImpl.class);
 
@@ -61,26 +67,41 @@ public class DeviceContextImpl implements DeviceContext, DeviceReplyProcessor {
     private final DeviceState deviceState;
     private final DataBroker dataBroker;
     private final XidGenerator xidGenerator;
-    private Map<Long, RequestContext> requests = new HashMap<Long, RequestContext>();
+    private final HashedWheelTimer hashedWheelTimer;
+    private Map<Long, RequestContext> requests = new TreeMap<>();
 
     private final Map<SwitchConnectionDistinguisher, ConnectionContext> auxiliaryConnectionContexts;
     private final TransactionChainManager txChainManager;
     private TranslatorLibrary translatorLibrary;
+    private AnyMessageTypeListener anyMessageTypeListener;
 
     @VisibleForTesting
     DeviceContextImpl(@Nonnull final ConnectionContext primaryConnectionContext,
-                      @Nonnull final DeviceState deviceState, @Nonnull final DataBroker dataBroker) {
+                      @Nonnull final DeviceState deviceState, @Nonnull final DataBroker dataBroker,
+                      @Nonnull final HashedWheelTimer hashedWheelTimer) {
         this.primaryConnectionContext = Preconditions.checkNotNull(primaryConnectionContext);
         this.deviceState = Preconditions.checkNotNull(deviceState);
         this.dataBroker = Preconditions.checkNotNull(dataBroker);
+        this.hashedWheelTimer = Preconditions.checkNotNull(hashedWheelTimer);
         xidGenerator = new XidGenerator();
         txChainManager = new TransactionChainManager(dataBroker, 500L);
         auxiliaryConnectionContexts = new HashMap<>();
         requests = new HashMap<>();
     }
 
+    /**
+     * This method is called from {@link DeviceManagerImpl} only. So we could say "posthandshake process finish"
+     * and we are able to set a scheduler for an automatic transaction submitting by time (0,5sec).
+     */
     void submitTransaction() {
         txChainManager.submitTransaction();
+        txChainManager.enableCounter();
+        hashedWheelTimer.newTimeout(new TimerTask() {
+            @Override
+            public void run(final Timeout timeout) throws Exception {
+                submitTransaction();
+            }
+        }, 0, TimeUnit.MILLISECONDS);
     }
 
     @Override
@@ -112,7 +133,7 @@ public class DeviceContextImpl implements DeviceContext, DeviceReplyProcessor {
 
     @Override
     public <T extends DataObject> void writeToTransaction(final LogicalDatastoreType store,
-            final InstanceIdentifier<T> path, final T data) {
+                                                          final InstanceIdentifier<T> path, final T data) {
         txChainManager.writeToTransaction(store, path, data);
     }
 
@@ -147,67 +168,92 @@ public class DeviceContextImpl implements DeviceContext, DeviceReplyProcessor {
         requests.put(xid.getValue(), requestFutureContext);
     }
 
+    @Override
+    public void attachAnyMessageTypeListener(final AnyMessageTypeListener anyMessageTypeListener) {
+        this.anyMessageTypeListener = anyMessageTypeListener;
+        primaryConnectionContext.getConnectionAdapter().setMessageListener(anyMessageTypeListener);
+    }
+
+    @Override
+    public AnyMessageTypeListener getAnyMessageTypeListener() {
+        return this.anyMessageTypeListener;
+    }
+
     @Override
     public void processReply(final OfHeader ofHeader) {
         final RequestContext requestContext = getRequests().get(ofHeader.getXid());
-        final SettableFuture replyFuture = requestContext.getFuture();
-        getRequests().remove(ofHeader.getXid());
-        RpcResult<OfHeader> rpcResult;
-
-        if(ofHeader instanceof Error) {
-            final Error error = (Error) ofHeader;
-            final String message = "Operation on device failed";
-            rpcResult= RpcResultBuilder
-                    .<OfHeader>failed()
-                    .withError(RpcError.ErrorType.APPLICATION, message, new DeviceDataException(message, error))
-                    .build();
+        if (null != requestContext) {
+            final SettableFuture replyFuture = requestContext.getFuture();
+            getRequests().remove(ofHeader.getXid());
+            RpcResult<OfHeader> rpcResult;
+            if (ofHeader instanceof Error) {
+                final Error error = (Error) ofHeader;
+                final String message = "Operation on device failed";
+                rpcResult = RpcResultBuilder
+                        .<OfHeader>failed()
+                        .withError(RpcError.ErrorType.APPLICATION, message, new DeviceDataException(message, error))
+                        .build();
+            } else {
+                rpcResult = RpcResultBuilder
+                        .<OfHeader>success()
+                        .withResult(ofHeader)
+                        .build();
+            }
+
+            replyFuture.set(rpcResult);
+            try {
+                requestContext.close();
+            } catch (final Exception e) {
+                LOG.error("Closing RequestContext failed: ", e);
+            }
         } else {
-            rpcResult = RpcResultBuilder
-                    .<OfHeader>success()
-                    .withResult(ofHeader)
-                    .build();
-        }
-
-        replyFuture.set(rpcResult);
-        try {
-            requestContext.close();
-        } catch (final Exception e) {
-            LOG.error("Closing RequestContext failed: ", e);
+            LOG.error("Can't find request context registered for xid : {}", ofHeader.getXid());
         }
     }
 
     @Override
-    public void processReply(final Xid xid, final List<OfHeader> ofHeaderList) {
+    public void processReply(final Xid xid, final List<MultipartReply> ofHeaderList) {
         final RequestContext requestContext = getRequests().get(xid.getValue());
-        final SettableFuture replyFuture = requestContext.getFuture();
-        getRequests().remove(xid.getValue());
-        final RpcResult<List<OfHeader>> rpcResult= RpcResultBuilder
-                                                .<List<OfHeader>>success()
-                                                .withResult(ofHeaderList)
-                                                .build();
-        replyFuture.set(rpcResult);
-        try {
-            requestContext.close();
-        } catch (final Exception e) {
-            LOG.error("Closing RequestContext failed: ", e);
+        if (null != requestContext) {
+            final SettableFuture replyFuture = requestContext.getFuture();
+            getRequests().remove(xid.getValue());
+            final RpcResult<List<MultipartReply>> rpcResult = RpcResultBuilder
+                    .<List<MultipartReply>>success()
+                    .withResult(ofHeaderList)
+                    .build();
+            replyFuture.set(rpcResult);
+            try {
+                requestContext.close();
+            } catch (final Exception e) {
+                LOG.error("Closing RequestContext failed: ", e);
+            }
+        } else {
+            LOG.error("Can't find request context registered for xid : {}", xid.getValue());
         }
     }
 
     @Override
     public void processException(final Xid xid, final DeviceDataException deviceDataException) {
+
+        LOG.trace("Processing exception for xid : {}", xid.getValue());
+
         final RequestContext requestContext = getRequests().get(xid.getValue());
 
-        final SettableFuture replyFuture = requestContext.getFuture();
-        getRequests().remove(xid.getValue());
-        final RpcResult<List<OfHeader>> rpcResult= RpcResultBuilder
-                .<List<OfHeader>>failed()
-                .withError(RpcError.ErrorType.APPLICATION, "Message processing failed", deviceDataException)
-                .build();
-        replyFuture.set(rpcResult);
-        try {
-            requestContext.close();
-        } catch (final Exception e) {
-            LOG.error("Closing RequestContext failed: ", e);
+        if (null != requestContext) {
+            final SettableFuture replyFuture = requestContext.getFuture();
+            getRequests().remove(xid.getValue());
+            final RpcResult<List<OfHeader>> rpcResult = RpcResultBuilder
+                    .<List<OfHeader>>failed()
+                    .withError(RpcError.ErrorType.APPLICATION, String.format("Message processing failed : %s", deviceDataException.getError()), deviceDataException)
+                    .build();
+            replyFuture.set(rpcResult);
+            try {
+                requestContext.close();
+            } catch (final Exception e) {
+                LOG.error("Closing RequestContext failed: ", e);
+            }
+        } else {
+            LOG.error("Can't find request context registered for xid : {}", xid.getValue());
         }
     }
 
@@ -218,7 +264,7 @@ public class DeviceContextImpl implements DeviceContext, DeviceReplyProcessor {
 
     @Override
     public void processPortStatusMessage(final PortStatusMessage portStatus) {
-        final TranslatorKey translatorKey = new TranslatorKey(portStatus.getVersion(), PortUpdateTranslator.class.getName());
+        final TranslatorKey translatorKey = new TranslatorKey(portStatus.getVersion(), PortStatusMessage.class.getName());
         final MessageTranslator<PortStatusMessage, FlowCapableNodeConnector> messageTranslator = translatorLibrary.lookupTranslator(translatorKey);
         final FlowCapableNodeConnector nodeConnector = messageTranslator.translate(portStatus, this, null);
         //TODO write into datastore
@@ -232,6 +278,12 @@ public class DeviceContextImpl implements DeviceContext, DeviceReplyProcessor {
         //TODO publish to MD-SAL
     }
 
+    @Override
+    public TranslatorLibrary oook() {
+        return translatorLibrary;
+    }
+
+    @Override
     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
         this.translatorLibrary = translatorLibrary;
     }
@@ -245,4 +297,17 @@ public class DeviceContextImpl implements DeviceContext, DeviceReplyProcessor {
             return new Xid(xid.incrementAndGet());
         }
     }
+
+    @Override
+    public RequestContext extractNextOutstandingMessage(long barrierXid) {
+        RequestContext nextMessage = null;
+        Iterator<Long> keyIterator = requests.keySet().iterator();
+        if (keyIterator.hasNext()) {
+            Long oldestXid = keyIterator.next();
+            if (oldestXid < barrierXid) {
+                nextMessage = requests.remove(oldestXid);
+            }
+        }
+        return nextMessage;
+    }
 }