Bug 2483 - Removed confusing WARN log on successful RPC
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / connection / ConnectionAdapterImpl.java
index 070d7d5e9c0088bf03d8f1eba991e6ebf78e4ea5..11e8336033e65cd78ee4daae3c04d91dfaa7d1d7 100644 (file)
@@ -13,7 +13,9 @@ import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
 import io.netty.util.concurrent.GenericFutureListener;
 
+import java.net.InetSocketAddress;
 import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.TimeUnit;
 
 import org.opendaylight.controller.sal.common.util.RpcErrors;
@@ -57,7 +59,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.Notification;
 import org.opendaylight.yangtools.yang.common.RpcError;
@@ -67,8 +68,10 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
 import com.google.common.cache.Cache;
 import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.RemovalCause;
 import com.google.common.cache.RemovalListener;
 import com.google.common.cache.RemovalNotification;
 import com.google.common.util.concurrent.ListenableFuture;
@@ -80,42 +83,63 @@ import com.google.common.util.concurrent.SettableFuture;
  * @author michal.polkorab
  */
 public class ConnectionAdapterImpl implements ConnectionFacade {
-
-    /** after this time, rpc future response objects will be thrown away (in minutes) */
+    /** after this time, RPC future response objects will be thrown away (in minutes) */
     public static final int RPC_RESPONSE_EXPIRATION = 1;
 
-    protected static final Logger LOG = LoggerFactory
+    /**
+     * Default depth of write queue, e.g. we allow these many messages
+     * to be queued up before blocking producers.
+     */
+    public static final int DEFAULT_QUEUE_DEPTH = 1024;
+
+    private static final Logger LOG = LoggerFactory
             .getLogger(ConnectionAdapterImpl.class);
+    private static final Exception QUEUE_FULL_EXCEPTION =
+            new RejectedExecutionException("Output queue is full");
 
     private static final String APPLICATION_TAG = "OPENFLOW_LIBRARY";
     private static final String TAG = "OPENFLOW";
-    private Channel channel;
-    private OpenflowProtocolListener messageListener;
+    private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
+            new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
+
+        @Override
+        public void onRemoval(
+                final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
+            if (! notification.getCause().equals(RemovalCause.EXPLICIT)) {
+                notification.getValue().discard();
+            }
+        }
+    };
+
     /** expiring cache for future rpcResponses */
-    protected Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> responseCache;
+    private final Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> responseCache;
+
+    private final ChannelOutboundQueue output;
+    private final Channel channel;
+
+    private ConnectionReadyListener connectionReadyListener;
+    private OpenflowProtocolListener messageListener;
     private SystemNotificationsListener systemListener;
     private boolean disconnectOccured = false;
 
-    protected ConnectionReadyListener connectionReadyListener;
-
     /**
      * default ctor
+     * @param channel the channel to be set - used for communication
+     * @param address client address (used only in case of UDP communication,
+     *  as there is no need to store address over tcp (stable channel))
      */
-    public ConnectionAdapterImpl() {
+    public ConnectionAdapterImpl(final Channel channel, final InetSocketAddress address) {
         responseCache = CacheBuilder.newBuilder()
                 .concurrencyLevel(1)
                 .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
-                .removalListener(new ResponseRemovalListener()).build();
+                .removalListener(REMOVAL_LISTENER).build();
+        this.channel = Preconditions.checkNotNull(channel);
+        this.output = new ChannelOutboundQueue(channel, DEFAULT_QUEUE_DEPTH);
+        output.setAddress(address);
+        channel.pipeline().addLast(output);
         LOG.debug("ConnectionAdapter created");
     }
 
-    /**
-     * @param channel the channel to be set - used for communication
-     */
-    public void setChannel(final Channel channel) {
-        this.channel = channel;
-    }
-
     @Override
     public Future<RpcResult<BarrierOutput>> barrier(final BarrierInput input) {
         return sendToSwitchExpectRpcResultFuture(
@@ -298,6 +322,19 @@ public class ConnectionAdapterImpl implements ConnectionFacade {
         }
     }
 
+    private <T> ListenableFuture<RpcResult<T>> enqueueMessage(final AbstractRpcListener<T> promise) {
+        LOG.debug("Submitting promise {}", promise);
+
+        if (!output.enqueue(promise)) {
+            LOG.debug("Message queue is full, rejecting execution");
+            promise.failedRpc(QUEUE_FULL_EXCEPTION);
+        } else {
+            LOG.debug("Promise enqueued successfully");
+        }
+
+        return promise.getResult();
+    }
+
     /**
      * sends given message to switch, sending result will be reported via return value
      * @param input message to send
@@ -310,13 +347,7 @@ public class ConnectionAdapterImpl implements ConnectionFacade {
      */
     private ListenableFuture<RpcResult<Void>> sendToSwitchFuture(
             final DataObject input, final String failureInfo) {
-        final SimpleRpcListener listener = new SimpleRpcListener(failureInfo);
-
-        LOG.debug("going to flush");
-        channel.writeAndFlush(input).addListener(listener);
-        LOG.debug("flushed");
-
-        return listener.getResult();
+        return enqueueMessage(new SimpleRpcListener(input, failureInfo));
     }
 
     /**
@@ -338,13 +369,8 @@ public class ConnectionAdapterImpl implements ConnectionFacade {
             final IN input, final Class<OUT> responseClazz, final String failureInfo) {
         final RpcResponseKey key = new RpcResponseKey(input.getXid(), responseClazz.getName());
         final ResponseExpectedRpcListener<OUT> listener =
-                new ResponseExpectedRpcListener<>(failureInfo, responseCache, key);
-
-        LOG.debug("going to flush");
-        channel.writeAndFlush(input).addListener(listener);
-        LOG.debug("flushed");
-
-        return listener.getResult();
+                new ResponseExpectedRpcListener<>(input, failureInfo, responseCache, key);
+        return enqueueMessage(listener);
     }
 
     /**
@@ -419,7 +445,7 @@ public class ConnectionAdapterImpl implements ConnectionFacade {
 
     @Override
     public void checkListeners() {
-        StringBuffer buffer =  new StringBuffer();
+        final StringBuilder buffer =  new StringBuilder();
         if (systemListener == null) {
             buffer.append("SystemListener ");
         }
@@ -430,28 +456,7 @@ public class ConnectionAdapterImpl implements ConnectionFacade {
             buffer.append("ConnectionReadyListener ");
         }
 
-        if (buffer.length() > 0) {
-            throw new IllegalStateException("Missing listeners: " + buffer.toString());
-        }
-    }
-
-    static class ResponseRemovalListener implements RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> {
-        @Override
-        public void onRemoval(
-                final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
-            notification.getValue().discard();
-        }
-    }
-
-    /**
-     * Class is used ONLY for exiting msgQueue processing thread
-     * @author michal.polkorab
-     */
-    static class ExitingDataObject implements DataObject {
-        @Override
-        public Class<? extends DataContainer> getImplementedInterface() {
-            return null;
-        }
+        Preconditions.checkState(buffer.length() == 0, "Missing listeners: %s", buffer.toString());
     }
 
     @Override
@@ -471,4 +476,8 @@ public class ConnectionAdapterImpl implements ConnectionFacade {
         this.connectionReadyListener = connectionReadyListener;
     }
 
+    @Override
+    public InetSocketAddress getRemoteAddress() {
+        return (InetSocketAddress) channel.remoteAddress();
+    }
 }