Bug 1588 - OFConstants.java moved to openflowplugin-api module
[openflowplugin.git] / openflowplugin / src / main / java / org / opendaylight / openflowplugin / openflow / md / core / ConnectionConductorImpl.java
index cd50acc4fdef9b4b03b625aa8b80b3f6adb1f1f7..0b5ff69c10dece33a9b4170baab38e715d1c33ed 100644 (file)
@@ -8,19 +8,25 @@
 
 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.ThreadPoolExecutor;
 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.api.OFConstants;
 import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
+import org.opendaylight.openflowplugin.openflow.md.core.session.PortFeaturesUtil;
 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.openflowplugin.openflow.md.queue.QueueKeeper.QueueType;
+import org.opendaylight.openflowplugin.openflow.md.queue.QueueKeeperFactory;
+import org.opendaylight.openflowplugin.openflow.md.queue.QueueProcessor;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.SwitchConfigFlag;
 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;
@@ -28,17 +34,21 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
 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.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;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus;
 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.protocol.rev130731.SetConfigInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestDescCaseBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestGroupFeaturesCaseBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestMeterFeaturesCaseBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestPortDescCaseBuilder;
 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;
@@ -48,127 +58,144 @@ 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, HandshakeListener {
 
-    private static final Logger LOG = LoggerFactory
+    /** ingress queue limit */
+    private static final int INGRESS_QUEUE_MAX_SIZE = 200;
+
+    protected static final Logger LOG = LoggerFactory
             .getLogger(ConnectionConductorImpl.class);
 
     /* variable to make BitMap-based negotiation enabled / disabled.
      * it will help while testing and isolating issues related to processing of
      * BitMaps from switches.
      */
-    private static final boolean isBitmapNegotiationEnable = true;
-    private LinkedBlockingQueue<Exception> errorQueue = new LinkedBlockingQueue<>();
+    private boolean isBitmapNegotiationEnable = true;
+    protected ErrorHandler errorHandler;
 
     private final ConnectionAdapter connectionAdapter;
-    private final List<Short> versionOrder;
     private ConnectionConductor.CONDUCTOR_STATE conductorState;
     private Short version;
 
-    private SwitchConnectionDistinguisher auxiliaryKey;
+    protected SwitchConnectionDistinguisher auxiliaryKey;
 
-    private SessionContext sessionContext;
+    protected SessionContext sessionContext;
 
-    private Map<Class<? extends DataObject>, Collection<IMDMessageListener>> listenerMapping;
+    private QueueProcessor<OfHeader, DataObject> queueProcessor;
+    private QueueKeeper<OfHeader> queue;
+    private ThreadPoolExecutor hsPool;
+    private HandshakeManager handshakeManager;
 
-    private boolean isFirstHelloNegotiation = true;
+    private boolean firstHelloProcessed;
+    
+    private PortFeaturesUtil portFeaturesUtils;
 
+    private int conductorId;
 
+    private int ingressMaxQueueSize;
 
+    
     /**
      * @param connectionAdapter
      */
     public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) {
+        this(connectionAdapter, INGRESS_QUEUE_MAX_SIZE);
+    }
+
+    /**
+     * @param connectionAdapter
+     * @param ingressMaxQueueSize ingress queue limit (blocking)
+     */
+    public ConnectionConductorImpl(ConnectionAdapter connectionAdapter, int ingressMaxQueueSize) {
         this.connectionAdapter = connectionAdapter;
+        this.ingressMaxQueueSize = ingressMaxQueueSize;
         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();
+        firstHelloProcessed = false;
+        handshakeManager = new HandshakeManagerImpl(connectionAdapter,
+                ConnectionConductor.versionOrder.get(0), ConnectionConductor.versionOrder);
+        handshakeManager.setUseVersionBitmap(isBitmapNegotiationEnable);
+        handshakeManager.setHandshakeListener(this);
+        portFeaturesUtils = PortFeaturesUtil.getInstance();
     }
 
     @Override
     public void init() {
+        int handshakeThreadLimit = 1;
+        hsPool = new ThreadPoolLoggingExecutor(handshakeThreadLimit , handshakeThreadLimit, 0L, 
+                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), 
+                "OFHandshake-"+conductorId);
+        
         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);
+        queue = QueueKeeperFactory.createFairQueueKeeper(queueProcessor, ingressMaxQueueSize);
     }
 
+    @Override
+    public void setQueueProcessor(QueueProcessor<OfHeader, DataObject> queueProcessor) {
+        this.queueProcessor = queueProcessor;
+    }
 
     /**
-     * send first hello message to switch
+     * @param errorHandler the errorHandler to set
      */
-    private void sendFirstHelloMessage() {
-        short highestVersion = versionOrder.get(0);
-        Long helloXid = 1L;
-        HelloInputBuilder helloInputbuilder = new HelloInputBuilder();
-        helloInputbuilder.setVersion(highestVersion);
-        helloInputbuilder.setXid(helloXid);
-        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);
-        } else {
-            LOG.debug("sending first hello message: version header={} ", highestVersion);
-        }
-        connectionAdapter.hello(helloInputbuilder.build());
-
+    @Override
+    public void setErrorHandler(ErrorHandler errorHandler) {
+        this.errorHandler = errorHandler;
+        handshakeManager.setErrorHandler(errorHandler);
     }
 
     @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());
+        enqueueMessage(errorMessage);
+    }
+
+    
+    /**
+     * @param message
+     */
+    private void enqueueMessage(OfHeader message) {
+        enqueueMessage(message, QueueType.DEFAULT);
+    }
+
+    /**
+     * @param message
+     * @param queueType enqueue type
+     */
+    private void enqueueMessage(OfHeader message, QueueType queueType) {
+        queue.push(message, this, queueType);
     }
 
     @Override
     public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
-        LOG.debug("experimenter received, type: "
-                + experimenterMessage.getExpType());
-        notifyListeners(ExperimenterMessage.class, experimenterMessage);
+        enqueueMessage(experimenterMessage);
     }
 
     @Override
     public void onFlowRemovedMessage(FlowRemovedMessage message) {
-        notifyListeners(FlowRemovedMessage.class, message);
+        enqueueMessage(message);
     }
 
 
@@ -179,190 +206,125 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
      * 2. If HelloMessage contains bitmap and common version found in bitmap
      *    then continue connection processing. if no common version found, just disconnect.
      * 3. If HelloMessage version is not supported, send HelloMessage with lower supported version.
-     *    If Hello message received again with not supported version, just disconnect.
-     *
-     *   TODO: Better to handle handshake into a maintainable innerclass which uses State-Pattern.
+     * 4. If Hello message received again with not supported version, just disconnect.
      */
     @Override
-    public void onHelloMessage(HelloMessage hello) {
-        // do handshake
-        LOG.info("handshake STARTED");
+    public void onHelloMessage(final HelloMessage hello) {
+        LOG.debug("processing HELLO.xid: {}", hello.getXid());
+        firstHelloProcessed = true;
         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();
-            }
-        }
-    }
-
-    /**
-     * send hello reply
-     * @param proposedVersion
-     * @param hello
-     */
-    private void sendHelloReply(Short proposedVersion, Long xid)
-    {
-        HelloInputBuilder helloBuilder = new HelloInputBuilder();
-        helloBuilder.setVersion(proposedVersion).setXid(xid);
-        connectionAdapter.hello(helloBuilder.build());
-    }
-
-
-    /**
-     * after handshake set features, register to session
-     * @param proposedVersion
-     * @param xId
-     */
-    private 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);
-        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);
-        }
+        HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
+                hello, handshakeManager, connectionAdapter);
+        hsPool.submit(handshakeStepWrapper);
     }
 
     /**
      * @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);
-        }
-    }
-
-    @Override
-    public void onMultipartReplyMessage(MultipartReplyMessage arg0) {
-        // TODO Auto-generated method stub
+    protected TimeUnit getMaxTimeoutUnit() {
+        // TODO:: get from configuration
+        return TimeUnit.MILLISECONDS;
     }
 
     @Override
-    public void onMultipartRequestMessage(MultipartRequestMessage arg0) {
-        // TODO Auto-generated method stub
+    public void onMultipartReplyMessage(MultipartReplyMessage message) {
+        enqueueMessage(message);
     }
 
     @Override
     public void onPacketInMessage(PacketInMessage message) {
-        notifyListeners(PacketInMessage.class, message);
+        enqueueMessage(message, QueueKeeper.QueueType.UNORDERED);
     }
 
     @Override
     public void onPortStatusMessage(PortStatusMessage message) {
-        this.getSessionContext().processPortStatusMsg(message);
-        notifyListeners(PortStatusMessage.class, message);
+        processPortStatusMsg(message);
+        enqueueMessage(message);
+    }
+    
+    protected void processPortStatusMsg(PortStatus msg) {
+        if (msg.getReason().getIntValue() == 2) {
+            updatePort(msg);
+        } else if (msg.getReason().getIntValue() == 0) {
+            updatePort(msg);
+        } else if (msg.getReason().getIntValue() == 1) {
+            deletePort(msg);
+        }
+    }
+    
+    protected void updatePort(PortStatus msg) {
+        Long portNumber = msg.getPortNo();        
+        Boolean portBandwidth = portFeaturesUtils.getPortBandwidth(msg);
+        
+        if(portBandwidth == null) {
+            LOG.debug("can't get bandwidth info from port: {}, aborting port update", msg.toString());
+        } else {
+            this.getSessionContext().getPhysicalPorts().put(portNumber, msg);
+            this.getSessionContext().getPortsBandwidth().put(portNumber, portBandwidth);                   
+        }            
+    }
+    
+    protected void deletePort(PortGrouping port) {
+        Long portNumber = port.getPortNo();
+        
+        this.getSessionContext().getPhysicalPorts().remove(portNumber);
+        this.getSessionContext().getPortsBandwidth().remove(portNumber);
     }
 
     @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, sessionCtx={}|auxId={}", sessionContext, auxiliaryKey);
+                    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());
+                        errorHandler.handleException(e, sessionContext);
+                        //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();
     }
 
     /**
@@ -380,9 +342,9 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
     }
 
     /**
-     * @param handshaking
+     * @param expectedState
      */
-    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);
@@ -395,60 +357,6 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
         sessionManager.invalidateOnDisconnect(this);
     }
 
-    /**
-     * find supported version based on remoteVersion
-     * @param remoteVersion
-     * @return
-     */
-    protected short proposeVersion(short remoteVersion) {
-        Short proposal = null;
-        for (short offer : versionOrder) {
-            if (offer <= remoteVersion) {
-                proposal = offer;
-                break;
-            }
-        }
-        if (proposal == null) {
-            throw new IllegalArgumentException("unsupported version: "
-                    + remoteVersion);
-        }
-        return proposal;
-    }
-
-    /**
-     * find common highest supported bitmap version
-     * @param list
-     * @return
-     */
-    protected short proposeBitmapVersion(List<Elements> list)
-    {
-        Short supportedHighestVersion = null;
-        if((null != list) && (0 != list.size()))
-        {
-           for(Elements element : list)
-           {
-              List<Boolean> bitmap = element.getVersionBitmap();
-              // check for version bitmap
-              for(short bitPos : versionOrder)
-              {
-                  // with all the version it should work.
-                  if(bitmap.get(bitPos % Integer.SIZE))
-                  {
-                      supportedHighestVersion = bitPos;
-                      break;
-                  }
-              }
-           }
-           if(null == supportedHighestVersion)
-            {
-                throw new IllegalArgumentException("unsupported bitmap version.");
-            }
-
-        }
-
-        return supportedHighestVersion;
-    }
-
     @Override
     public Short getVersion() {
         return version;
@@ -456,7 +364,17 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
 
     @Override
     public Future<Boolean> disconnect() {
-        return connectionAdapter.disconnect();
+        LOG.trace("disconnecting: sessionCtx={}|auxId={}", sessionContext, auxiliaryKey);
+
+        Future<Boolean> result = null;
+        if (connectionAdapter.isAlive()) {
+            result = connectionAdapter.disconnect();
+        } else {
+            LOG.debug("connection already disconnected");
+            result = Futures.immediateFuture(true);
+        }
+
+        return result;
     }
 
     @Override
@@ -479,37 +397,136 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
         return sessionContext;
     }
 
+    @Override
+    public ConnectionAdapter getConnectionAdapter() {
+        return connectionAdapter;
+    }
+
+    @Override
+    public void onConnectionReady() {
+        LOG.debug("connection is ready-to-use");
+        if (! firstHelloProcessed) {
+            HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
+                    null, handshakeManager, connectionAdapter);
+            hsPool.execute(handshakeStepWrapper);
+            firstHelloProcessed = true;
+        } else {
+            LOG.debug("already touched by hello message");
+        }
+    }
+
+    @Override
+    public void onHandshakeSuccessfull(GetFeaturesOutput featureOutput,
+            Short negotiatedVersion) {
+        postHandshakeBasic(featureOutput, negotiatedVersion);
+        
+        // post-handshake actions
+        if(version == OFConstants.OFP_VERSION_1_3){
+            setDefaultConfig();
+            requestPorts();
+            requestGroupFeatures();
+            requestMeterFeatures();
+        } else if (version == OFConstants.OFP_VERSION_1_0) {
+            //  Because the GetFeaturesOutput contains information about the port
+            //  in OF1.0 (that we would otherwise get from the PortDesc) we have to pass
+            //  it up for parsing to convert into a NodeConnectorUpdate
+            enqueueMessage(featureOutput);
+        }
+        
+        requestDesc();
+    }
+
     /**
-     * @param listenerMapping the listenerMapping to set
+     * used by tests
+     * @param featureOutput
+     * @param negotiatedVersion
+     */
+    protected void postHandshakeBasic(GetFeaturesOutput featureOutput,
+            Short negotiatedVersion) {
+        version = negotiatedVersion;
+        conductorState = CONDUCTOR_STATE.WORKING;
+        OFSessionUtil.registerSession(this, featureOutput, negotiatedVersion);
+        hsPool.shutdown();
+        hsPool.purge();
+    }
+
+    private void setDefaultConfig(){
+        SetConfigInputBuilder builder = new SetConfigInputBuilder();
+        builder.setVersion(getVersion());
+        builder.setXid(getSessionContext().getNextXid());
+        SwitchConfigFlag flag = SwitchConfigFlag.FRAGNORMAL;
+        builder.setFlags(flag);
+        builder.setMissSendLen(OFConstants.OFPCML_NO_BUFFER);
+        getConnectionAdapter().setConfig(builder.build());
+    }
+
+    /*
+     *  Send an OFPMP_DESC request message to the switch
      */
-    public void setListenerMapping(
-            Map<Class<? extends DataObject>, Collection<IMDMessageListener>> listenerMapping) {
-        //TODO: adjust the listener interface
-        this.listenerMapping = listenerMapping;
+    private void requestDesc() {
+        MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder();
+        builder.setType(MultipartType.OFPMPDESC);
+        builder.setVersion(getVersion());
+        builder.setFlags(new MultipartRequestFlags(false));
+        builder.setMultipartRequestBody(new MultipartRequestDescCaseBuilder().build());
+        builder.setXid(getSessionContext().getNextXid());
+        getConnectionAdapter().multipartRequest(builder.build());
+    }
+
+    private void requestPorts() {
+        MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder();
+        builder.setType(MultipartType.OFPMPPORTDESC);
+        builder.setVersion(getVersion());
+        builder.setFlags(new MultipartRequestFlags(false));
+        builder.setMultipartRequestBody(new MultipartRequestPortDescCaseBuilder().build());
+        builder.setXid(getSessionContext().getNextXid());
+        getConnectionAdapter().multipartRequest(builder.build());
+    }
+    private void requestGroupFeatures(){
+        MultipartRequestInputBuilder mprInput = new MultipartRequestInputBuilder();
+        mprInput.setType(MultipartType.OFPMPGROUPFEATURES);
+        mprInput.setVersion(getVersion());
+        mprInput.setFlags(new MultipartRequestFlags(false));
+        mprInput.setXid(getSessionContext().getNextXid());
+
+        MultipartRequestGroupFeaturesCaseBuilder mprGroupFeaturesBuild = 
+                new MultipartRequestGroupFeaturesCaseBuilder();
+        mprInput.setMultipartRequestBody(mprGroupFeaturesBuild.build());
+
+        LOG.debug("Send group features statistics request :{}",mprGroupFeaturesBuild);
+        getConnectionAdapter().multipartRequest(mprInput.build());
+        
+    }
+    private void requestMeterFeatures(){
+        MultipartRequestInputBuilder mprInput = new MultipartRequestInputBuilder();
+        mprInput.setType(MultipartType.OFPMPMETERFEATURES);
+        mprInput.setVersion(getVersion());
+        mprInput.setFlags(new MultipartRequestFlags(false));
+        mprInput.setXid(getSessionContext().getNextXid());
+
+        MultipartRequestMeterFeaturesCaseBuilder mprMeterFeaturesBuild =
+                new MultipartRequestMeterFeaturesCaseBuilder();
+        mprInput.setMultipartRequestBody(mprMeterFeaturesBuild.build());
+
+        LOG.debug("Send meter features statistics request :{}",mprMeterFeaturesBuild);
+        getConnectionAdapter().multipartRequest(mprInput.build());
+        
     }
-
     /**
-     * @param messageType
-     * @param message
+     * @param isBitmapNegotiationEnable the isBitmapNegotiationEnable to set
      */
-    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);
-        }
+    public void setBitmapNegotiationEnable(
+            boolean isBitmapNegotiationEnable) {
+        this.isBitmapNegotiationEnable = isBitmapNegotiationEnable;
     }
 
+    protected void shutdownPool() {
+        hsPool.shutdownNow();
+        LOG.debug("pool is terminated: {}", hsPool.isTerminated());
+    }
+    
     @Override
-    public ConnectionAdapter getConnectionAdapter() {
-        return connectionAdapter;
+    public void setId(int conductorId) {
+        this.conductorId = conductorId;
     }
 }