site improvement, warnings removal, applied queueKeeper, fixed tests, errorHandler...
[openflowplugin.git] / openflowplugin / src / main / java / org / opendaylight / openflowplugin / openflow / md / core / ConnectionConductorImpl.java
index cd50acc4fdef9b4b03b625aa8b80b3f6adb1f1f7..cfc4011453ff8c9f4d79b1d5ac34cb7031d625b4 100644 (file)
@@ -8,19 +8,16 @@
 
 package org.opendaylight.openflowplugin.openflow.md.core;
 
-import java.util.ArrayList;
-import java.util.Collection;
 import java.util.List;
-import java.util.Map;
 import java.util.concurrent.Future;
-import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
 
 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
+import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
 import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
 import org.opendaylight.openflowplugin.openflow.md.core.session.SessionContext;
 import org.opendaylight.openflowplugin.openflow.md.core.session.SessionManager;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.HelloElementType;
+import org.opendaylight.openflowplugin.openflow.md.queue.QueueKeeper;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInputBuilder;
@@ -30,7 +27,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestMessage;
@@ -38,26 +35,23 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.hello.Elements;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.hello.ElementsBuilder;
 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.DataObject;
 import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Futures;
 
 /**
  * @author mirehak
  */
 public class ConnectionConductorImpl implements OpenflowProtocolListener,
-        SystemNotificationsListener, ConnectionConductor {
+        SystemNotificationsListener, ConnectionConductor, ConnectionReadyListener {
 
-    private static final Logger LOG = LoggerFactory
+    protected static final Logger LOG = LoggerFactory
             .getLogger(ConnectionConductorImpl.class);
 
     /* variable to make BitMap-based negotiation enabled / disabled.
@@ -65,10 +59,9 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
      * BitMaps from switches.
      */
     private static final boolean isBitmapNegotiationEnable = true;
-    private LinkedBlockingQueue<Exception> errorQueue = new LinkedBlockingQueue<>();
+    private ErrorHandler errorHandler;
 
     private final ConnectionAdapter connectionAdapter;
-    private final List<Short> versionOrder;
     private ConnectionConductor.CONDUCTOR_STATE conductorState;
     private Short version;
 
@@ -76,9 +69,10 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
 
     private SessionContext sessionContext;
 
-    private Map<Class<? extends DataObject>, Collection<IMDMessageListener>> listenerMapping;
+    protected boolean isFirstHelloNegotiation = true;
 
-    private boolean isFirstHelloNegotiation = true;
+    // TODO: use appropriate interface instead of Object
+    private QueueKeeper<Object> queueKeeper;
 
 
 
@@ -88,87 +82,87 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
     public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) {
         this.connectionAdapter = connectionAdapter;
         conductorState = CONDUCTOR_STATE.HANDSHAKING;
-        versionOrder = Lists.newArrayList((short) 0x04, (short) 0x01);
-        // TODO: add a thread pool to handle ErrorQueueHandler
-        new Thread(new ErrorQueueHandler(errorQueue)).start();
     }
 
     @Override
     public void init() {
         connectionAdapter.setMessageListener(this);
         connectionAdapter.setSystemListener(this);
-        //TODO : Wait for library to provide interface from which we can send first hello message
-//        sendFirstHelloMessage();
+        connectionAdapter.setConnectionReadyListener(this);
+    }
+    
+    /**
+     * @param queueKeeper the queueKeeper to set
+     */
+    @Override
+    public void setQueueKeeper(QueueKeeper<Object> queueKeeper) {
+        this.queueKeeper = queueKeeper;
     }
 
+    /**
+     * @param errorHandler the errorHandler to set
+     */
+    @Override
+    public void setErrorHandler(ErrorHandler errorHandler) {
+        this.errorHandler = errorHandler;
+    }
 
     /**
      * send first hello message to switch
      */
-    private void sendFirstHelloMessage() {
-        short highestVersion = versionOrder.get(0);
-        Long helloXid = 1L;
-        HelloInputBuilder helloInputbuilder = new HelloInputBuilder();
-        helloInputbuilder.setVersion(highestVersion);
-        helloInputbuilder.setXid(helloXid);
+    protected void sendFirstHelloMessage() {
+        Short highestVersion = ConnectionConductor.versionOrder.get(0);
+        Long helloXid = 21L;
+        HelloInput helloInput = null;
+        
         if (isBitmapNegotiationEnable) {
-            int elementsCount = highestVersion / Integer.SIZE;
-            ElementsBuilder elementsBuilder = new ElementsBuilder();
-
-            List<Elements> elementList = new ArrayList<Elements>();
-            int orderIndex = versionOrder.size();
-            int value = versionOrder.get(--orderIndex);
-            for (int index = 0; index <= elementsCount; index++) {
-                List<Boolean> booleanList = new ArrayList<Boolean>();
-                for (int i = 0; i < Integer.SIZE; i++) {
-                    if (value == ((index * Integer.SIZE) + i)) {
-                        booleanList.add(true);
-                        value = (orderIndex == 0) ? highestVersion : versionOrder.get(--orderIndex);
-                    } else {
-                        booleanList.add(false);
-                    }
-                }
-                elementsBuilder.setType(HelloElementType.forValue(1));
-                elementsBuilder.setVersionBitmap(booleanList);
-                elementList.add(elementsBuilder.build());
-            }
-            helloInputbuilder.setElements(elementList);
-            LOG.debug("sending first hello message: version header={} , version bitmap={}", highestVersion, elementList);
+            helloInput = MessageFactory.createHelloInput(highestVersion, helloXid, ConnectionConductor.versionOrder);
+            LOG.debug("sending first hello message: vertsion header={} , version bitmap={}", 
+                    highestVersion, MessageFactory.digVersions(helloInput.getElements()));
         } else {
+            helloInput = MessageFactory.createHelloInput(highestVersion, helloXid);
             LOG.debug("sending first hello message: version header={} ", highestVersion);
         }
-        connectionAdapter.hello(helloInputbuilder.build());
-
+        
+        try {
+            RpcResult<Void> helloResult = connectionAdapter.hello(helloInput).get(getMaxTimeout(), getMaxTimeoutUnit());
+            smokeRpc(helloResult);
+            LOG.debug("FIRST HELLO sent.");
+        } catch (Throwable e) {
+            LOG.debug("FIRST HELLO sending failed.");
+            errorHandler.handleException(e, getSessionContext());
+        }
     }
 
     @Override
-    public void onEchoRequestMessage(EchoRequestMessage echoRequestMessage) {
-        LOG.debug("echo request received: " + echoRequestMessage.getXid());
-        EchoReplyInputBuilder builder = new EchoReplyInputBuilder();
-        builder.setVersion(echoRequestMessage.getVersion());
-        builder.setXid(echoRequestMessage.getXid());
-        builder.setData(echoRequestMessage.getData());
-
-        connectionAdapter.echoReply(builder.build());
+    public void onEchoRequestMessage(final EchoRequestMessage echoRequestMessage) {
+        new Thread(new Runnable() {
+            @Override
+            public void run() {
+                LOG.debug("echo request received: " + echoRequestMessage.getXid());
+                EchoReplyInputBuilder builder = new EchoReplyInputBuilder();
+                builder.setVersion(echoRequestMessage.getVersion());
+                builder.setXid(echoRequestMessage.getXid());
+                builder.setData(echoRequestMessage.getData());
+                
+                getConnectionAdapter().echoReply(builder.build());
+            }
+        }).start();            
     }
 
     @Override
     public void onErrorMessage(ErrorMessage errorMessage) {
-        // TODO Auto-generated method stub
-        LOG.debug("error received, type: " + errorMessage.getType()
-                + "; code: " + errorMessage.getCode());
+        queueKeeper.push(ErrorMessage.class, errorMessage, this);
     }
 
     @Override
     public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
-        LOG.debug("experimenter received, type: "
-                + experimenterMessage.getExpType());
-        notifyListeners(ExperimenterMessage.class, experimenterMessage);
+        queueKeeper.push(ExperimenterMessage.class, experimenterMessage, this);
     }
 
     @Override
     public void onFlowRemovedMessage(FlowRemovedMessage message) {
-        notifyListeners(FlowRemovedMessage.class, message);
+        queueKeeper.push(FlowRemovedMessage.class, message, this);
     }
 
 
@@ -184,57 +178,63 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
      *   TODO: Better to handle handshake into a maintainable innerclass which uses State-Pattern.
      */
     @Override
-    public void onHelloMessage(HelloMessage hello) {
+    public void onHelloMessage(final HelloMessage hello) {
         // do handshake
-        LOG.info("handshake STARTED");
-        checkState(CONDUCTOR_STATE.HANDSHAKING);
-
-        Short remoteVersion = hello.getVersion();
-        List<Elements> elements = hello.getElements();
-        long xid = hello.getXid();
-        short proposedVersion;
-        LOG.debug("Hello message version={} and bitmap={}", remoteVersion, elements);
-        try {
-            // find the version from header version field
-            proposedVersion = proposeVersion(remoteVersion);
-
-        } catch (IllegalArgumentException e) {
-            handleException(e);
-            connectionAdapter.disconnect();
-            throw e;
-        }
 
-        // sent version is equal to remote --> version is negotiated
-        if (proposedVersion == remoteVersion) {
-            LOG.debug("sending helloReply as version in header is supported: {}", proposedVersion);
-            sendHelloReply(proposedVersion, ++xid);
-            postHandshake(proposedVersion, ++xid);
-
-        } else if (isBitmapNegotiationEnable && null != elements && 0 != elements.size()) {
-            try {
-                // hello contains version bitmap, checking highest common
-                // version in bitmap
-                proposedVersion = proposeBitmapVersion(elements);
-            } catch (IllegalArgumentException ex) {
-                handleException(ex);
-                connectionAdapter.disconnect();
-                throw ex;
-            }
-            LOG.debug("sending helloReply for common bitmap version : {}", proposedVersion);
-            sendHelloReply(proposedVersion, ++xid);
-            postHandshake(proposedVersion, ++xid);
-        } else {
-            if (isFirstHelloNegotiation) {
-                isFirstHelloNegotiation = false;
-                LOG.debug("sending helloReply for lowest supported version : {}", proposedVersion);
-                // send hello reply with lower version number supported
-                sendHelloReply(proposedVersion, ++xid);
-            } else {
-                // terminate the connection.
-                LOG.debug("Version negotiation failed. unsupported version : {}", remoteVersion);
-                connectionAdapter.disconnect();
+        new Thread(new Runnable() {
+            @Override
+            public void run() {
+                LOG.info("handshake STARTED");
+                checkState(CONDUCTOR_STATE.HANDSHAKING);
+                
+                Short remoteVersion = hello.getVersion();
+                List<Elements> elements = hello.getElements();
+                Long xid = hello.getXid();
+                Short proposedVersion;
+                LOG.debug("Hello message version={} and bitmap={}", remoteVersion, MessageFactory.digVersions(elements));
+                try {
+                    // find the version from header version field
+                    proposedVersion = proposeVersion(remoteVersion);
+                    
+                } catch (IllegalArgumentException e) {
+                    errorHandler.handleException(e, getSessionContext());
+                    getConnectionAdapter().disconnect();
+                    return;
+                }
+                
+                // sent version is equal to remote --> version is negotiated
+                if (proposedVersion == remoteVersion) {
+                    LOG.debug("sending helloReply as version in header is supported: {}", proposedVersion);
+                    sendHelloReply(proposedVersion, ++xid);
+                    postHandshake(proposedVersion, ++xid);
+                    
+                } else if (isBitmapNegotiationEnable && null != elements && 0 != elements.size()) {
+                    try {
+                        // hello contains version bitmap, checking highest common
+                        // version in bitmap
+                        proposedVersion = proposeBitmapVersion(elements);
+                    } catch (IllegalArgumentException ex) {
+                        errorHandler.handleException(ex, getSessionContext());
+                        getConnectionAdapter().disconnect();
+                        return;
+                    }
+                    LOG.debug("sending helloReply for common bitmap version : {}", proposedVersion);
+                    sendHelloReply(proposedVersion, ++xid);
+                    postHandshake(proposedVersion, ++xid);
+                } else {
+                    if (isFirstHelloNegotiation) {
+                        isFirstHelloNegotiation = false;
+                        LOG.debug("sending helloReply for lowest supported version : {}", proposedVersion);
+                        // send hello reply with lower version number supported
+                        sendHelloReply(proposedVersion, ++xid);
+                    } else {
+                        // terminate the connection.
+                        LOG.debug("Version negotiation failed. unsupported version : {}", remoteVersion);
+                        getConnectionAdapter().disconnect();
+                    }
+                }
             }
-        }
+        }).start();
     }
 
     /**
@@ -242,127 +242,159 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
      * @param proposedVersion
      * @param hello
      */
-    private void sendHelloReply(Short proposedVersion, Long xid)
+    protected void sendHelloReply(Short proposedVersion, Long xid)
     {
-        HelloInputBuilder helloBuilder = new HelloInputBuilder();
-        helloBuilder.setVersion(proposedVersion).setXid(xid);
-        connectionAdapter.hello(helloBuilder.build());
+        HelloInput helloMsg = MessageFactory.createHelloInput(proposedVersion, xid);
+        RpcResult<Void> result;
+        try {
+            result = connectionAdapter.hello(helloMsg).get(getMaxTimeout(), getMaxTimeoutUnit());
+            smokeRpc(result);
+        } catch (Throwable e) {
+            errorHandler.handleException(e, getSessionContext());
+        }
     }
 
 
+    /**
+     * @param futureResult
+     * @throws Throwable 
+     */
+    private static void smokeRpc(RpcResult<?> result) throws Throwable {
+        if (!result.isSuccessful()) {
+            Throwable firstCause = null;
+            StringBuffer sb = new StringBuffer();
+            for (RpcError error : result.getErrors()) {
+                if (firstCause != null) {
+                    firstCause = error.getCause();
+                }
+                
+                sb.append("rpcError:").append(error.getCause().getMessage()).append(";");
+            }
+            throw new Exception(sb.toString(), firstCause);
+        }
+    }
+
     /**
      * after handshake set features, register to session
      * @param proposedVersion
      * @param xId
      */
-    private void postHandshake(Short proposedVersion, Long xid) {
+    protected void postHandshake(Short proposedVersion, Long xid) {
         // set version
         version = proposedVersion;
         LOG.debug("version set: " + proposedVersion);
         // request features
         GetFeaturesInputBuilder featuresBuilder = new GetFeaturesInputBuilder();
-            featuresBuilder.setVersion(version).setXid(xid);
+        featuresBuilder.setVersion(version).setXid(xid);
         LOG.debug("sending feature request for version={} and xid={}", version, xid);
         Future<RpcResult<GetFeaturesOutput>> featuresFuture = connectionAdapter
                 .getFeatures(featuresBuilder.build());
         LOG.debug("waiting for features");
-        RpcResult<GetFeaturesOutput> rpcFeatures;
         try {
-            rpcFeatures = featuresFuture.get(getMaxTimeout(),
-                    TimeUnit.MILLISECONDS);
-            if (!rpcFeatures.isSuccessful()) {
-                LOG.error("obtained features problem: {}"
-                        , rpcFeatures.getErrors());
-            } else {
-                GetFeaturesOutput featureOutput =  rpcFeatures.getResult();
-                LOG.debug("obtained features: datapathId={}"
-                        , featureOutput.getDatapathId());
-                conductorState = CONDUCTOR_STATE.WORKING;
-
-                OFSessionUtil.registerSession(this,
-                        featureOutput, version);
-                LOG.info("handshake SETTLED: datapathId={}, auxiliaryId={}", featureOutput.getDatapathId(), featureOutput.getAuxiliaryId());
-            }
-        } catch (Exception e) {
-            handleException(e);
+            RpcResult<GetFeaturesOutput> rpcFeatures = 
+                    featuresFuture.get(getMaxTimeout(), getMaxTimeoutUnit());
+            smokeRpc(rpcFeatures);
+            
+            GetFeaturesOutput featureOutput =  rpcFeatures.getResult();
+            LOG.debug("obtained features: datapathId={}",
+                    featureOutput.getDatapathId());
+            LOG.debug("obtained features: auxiliaryId={}",
+                    featureOutput.getAuxiliaryId());
+            conductorState = CONDUCTOR_STATE.WORKING;
+
+            OFSessionUtil.registerSession(this,
+                    featureOutput, version);
+            LOG.info("handshake SETTLED: datapathId={}, auxiliaryId={}", featureOutput.getDatapathId(), featureOutput.getAuxiliaryId());
+        } catch (Throwable e) {
+            //handshake failed
+            LOG.error("issuing disconnect during handshake, reason: "+e.getMessage());
+            errorHandler.handleException(e, getSessionContext());
+            disconnect();
         }
     }
 
     /**
      * @return rpc-response timeout in [ms]
      */
-    private long getMaxTimeout() {
+    protected long getMaxTimeout() {
         // TODO:: get from configuration
         return 2000;
     }
-
+    
     /**
-     * @param e
+     * @return milliseconds
      */
-    private void handleException(Exception e) {
-        try {
-            errorQueue.put(e);
-        } catch (InterruptedException e1) {
-            LOG.error(e1.getMessage(), e1);
-        }
+    protected TimeUnit getMaxTimeoutUnit() {
+        // TODO:: get from configuration
+        return TimeUnit.MILLISECONDS;
     }
 
     @Override
-    public void onMultipartReplyMessage(MultipartReplyMessage arg0) {
-        // TODO Auto-generated method stub
+    public void onMultipartReplyMessage(MultipartReplyMessage message) {
+        queueKeeper.push(MultipartReplyMessage.class, message, this);
     }
 
     @Override
-    public void onMultipartRequestMessage(MultipartRequestMessage arg0) {
-        // TODO Auto-generated method stub
+    public void onMultipartRequestMessage(MultipartRequestMessage message) {
+        queueKeeper.push(MultipartRequestMessage.class, message, this);
     }
 
     @Override
     public void onPacketInMessage(PacketInMessage message) {
-        notifyListeners(PacketInMessage.class, message);
+        queueKeeper.push(PacketInMessage.class, message, this);
     }
 
     @Override
     public void onPortStatusMessage(PortStatusMessage message) {
         this.getSessionContext().processPortStatusMsg(message);
-        notifyListeners(PortStatusMessage.class, message);
+        queueKeeper.push(PortStatusMessage.class, message, this);
     }
 
     @Override
     public void onSwitchIdleEvent(SwitchIdleEvent notification) {
-        if (!CONDUCTOR_STATE.WORKING.equals(conductorState)) {
-            // idle state in any other conductorState than WORKING means real
-            // problem and wont be handled by echoReply, but disconnection
-            OFSessionUtil.getSessionManager().invalidateOnDisconnect(this);
-        } else {
-            LOG.debug("first idle state occured");
-            EchoInputBuilder builder = new EchoInputBuilder();
-            builder.setVersion(version);
-            // TODO: get xid from sessionContext
-            builder.setXid(42L);
-
-            Future<RpcResult<EchoOutput>> echoReplyFuture = connectionAdapter
-                    .echo(builder.build());
-
-            try {
-                // TODO: read timeout from config
-                RpcResult<EchoOutput> echoReplyValue = echoReplyFuture.get(5,
-                        TimeUnit.SECONDS);
-                if (echoReplyValue.isSuccessful()) {
-                    conductorState = CONDUCTOR_STATE.WORKING;
+        new Thread(new Runnable() {
+            @Override
+            public void run() {
+                if (!CONDUCTOR_STATE.WORKING.equals(getConductorState())) {
+                    // idle state in any other conductorState than WORKING means real
+                    // problem and wont be handled by echoReply, but disconnection
+                    disconnect();
+                    OFSessionUtil.getSessionManager().invalidateOnDisconnect(ConnectionConductorImpl.this);
                 } else {
-                    for (RpcError replyError : echoReplyValue.getErrors()) {
-                        Throwable cause = replyError.getCause();
-                        LOG.error(
-                                "while receiving echoReply in TIMEOUTING state: "
-                                        + cause.getMessage(), cause);
+                    LOG.debug("first idle state occured");
+                    EchoInputBuilder builder = new EchoInputBuilder();
+                    builder.setVersion(getVersion());
+                    builder.setXid(getSessionContext().getNextXid());
+                    
+                    Future<RpcResult<EchoOutput>> echoReplyFuture = getConnectionAdapter()
+                            .echo(builder.build());
+                    
+                    try {
+                        RpcResult<EchoOutput> echoReplyValue = echoReplyFuture.get(getMaxTimeout(),
+                                getMaxTimeoutUnit());
+                        if (echoReplyValue.isSuccessful()) {
+                            setConductorState(CONDUCTOR_STATE.WORKING);
+                        } else {
+                            for (RpcError replyError : echoReplyValue.getErrors()) {
+                                Throwable cause = replyError.getCause();
+                                LOG.error(
+                                        "while receiving echoReply in TIMEOUTING state: "
+                                                + cause.getMessage(), cause);
+                            }
+                            //switch issue occurred
+                            throw new Exception("switch issue occurred");
+                        }
+                    } catch (Exception e) {
+                        LOG.error("while waiting for echoReply in TIMEOUTING state: "
+                                + e.getMessage(), e);
+                        //switch is not responding
+                        disconnect();
+                        OFSessionUtil.getSessionManager().invalidateOnDisconnect(ConnectionConductorImpl.this);
                     }
                 }
-            } catch (Exception e) {
-                LOG.error("while waiting for echoReply in TIMEOUTING state: "
-                        + e.getMessage(), e);
             }
-        }
+            
+        }).start();
     }
 
     /**
@@ -382,7 +414,7 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
     /**
      * @param handshaking
      */
-    private void checkState(CONDUCTOR_STATE expectedState) {
+    protected void checkState(CONDUCTOR_STATE expectedState) {
         if (!conductorState.equals(expectedState)) {
             throw new IllegalStateException("Expected state: " + expectedState
                     + ", actual state:" + conductorState);
@@ -402,7 +434,7 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
      */
     protected short proposeVersion(short remoteVersion) {
         Short proposal = null;
-        for (short offer : versionOrder) {
+        for (short offer : ConnectionConductor.versionOrder) {
             if (offer <= remoteVersion) {
                 proposal = offer;
                 break;
@@ -420,7 +452,7 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
      * @param list
      * @return
      */
-    protected short proposeBitmapVersion(List<Elements> list)
+    protected Short proposeBitmapVersion(List<Elements> list)
     {
         Short supportedHighestVersion = null;
         if((null != list) && (0 != list.size()))
@@ -429,7 +461,7 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
            {
               List<Boolean> bitmap = element.getVersionBitmap();
               // check for version bitmap
-              for(short bitPos : versionOrder)
+              for(short bitPos : ConnectionConductor.versionOrder)
               {
                   // with all the version it should work.
                   if(bitmap.get(bitPos % Integer.SIZE))
@@ -456,7 +488,17 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
 
     @Override
     public Future<Boolean> disconnect() {
-        return connectionAdapter.disconnect();
+        LOG.info("disconnecting: sessionCtx="+sessionContext+"|auxId="+auxiliaryKey);
+        
+        Future<Boolean> result = null;
+        if (connectionAdapter.isAlive()) {
+            result = connectionAdapter.disconnect();
+        } else {
+            LOG.debug("connection already disconnected");
+            result = Futures.immediateFuture(true);
+        }
+        
+        return result; 
     }
 
     @Override
@@ -478,38 +520,21 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
     public SessionContext getSessionContext() {
         return sessionContext;
     }
-
-    /**
-     * @param listenerMapping the listenerMapping to set
-     */
-    public void setListenerMapping(
-            Map<Class<? extends DataObject>, Collection<IMDMessageListener>> listenerMapping) {
-        //TODO: adjust the listener interface
-        this.listenerMapping = listenerMapping;
-    }
-
-    /**
-     * @param messageType
-     * @param message
-     */
-    private void notifyListeners(Class<? extends DataObject> messageType, DataObject message) {
-        Collection<IMDMessageListener> listeners = listenerMapping.get(messageType);
-        if (listeners != null) {
-                for (IMDMessageListener listener : listeners) {
-                    // Pass cookie only for PACKT_IN
-                    if ( messageType.equals("PacketInMessage.class")){
-                        listener.receive(this.getAuxiliaryKey(), this.getSessionContext(), message);
-                    } else {
-                        listener.receive(null, this.getSessionContext(), message);
-                    }
-                }
-        } else {
-            LOG.warn("No listeners for this message Type {}", messageType);
-        }
-    }
-
+    
     @Override
     public ConnectionAdapter getConnectionAdapter() {
         return connectionAdapter;
     }
+
+    @Override
+    public void onConnectionReady() {
+        LOG.debug("connection is ready-to-use");
+        new Thread(new Runnable() {
+            @Override
+            public void run() {
+                sendFirstHelloMessage();
+            }
+        }).start();
+    }
+    
 }