1) Fixed minor issue caused by change in port statistics models
[openflowplugin.git] / openflowplugin / src / main / java / org / opendaylight / openflowplugin / openflow / md / core / ConnectionConductorImpl.java
index 985e54a130234cf90f3fbaadc76235078e10a1f8..98e9037eb18f29ee5161f7be18816f2e9c7098d3 100644 (file)
@@ -8,21 +8,21 @@
 
 package org.opendaylight.openflowplugin.openflow.md.core;
 
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
-import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
 
 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
+import org.opendaylight.openflowplugin.openflow.md.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.openflowplugin.openflow.md.queue.QueueKeeper;
+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.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,16 +30,20 @@ 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.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;
+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.Port;
+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.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;
@@ -55,7 +59,7 @@ import com.google.common.util.concurrent.Futures;
  * @author mirehak
  */
 public class ConnectionConductorImpl implements OpenflowProtocolListener,
-        SystemNotificationsListener, ConnectionConductor, ConnectionReadyListener {
+        SystemNotificationsListener, ConnectionConductor, ConnectionReadyListener, HandshakeListener {
 
     protected static final Logger LOG = LoggerFactory
             .getLogger(ConnectionConductorImpl.class);
@@ -64,10 +68,10 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
      * 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;
 
-    protected final ConnectionAdapter connectionAdapter;
+    private final ConnectionAdapter connectionAdapter;
     private ConnectionConductor.CONDUCTOR_STATE conductorState;
     private Short version;
 
@@ -75,11 +79,13 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
 
     private SessionContext sessionContext;
 
-    private Map<Class<? extends DataObject>, Collection<IMDMessageListener>> listenerMapping;
-
-    protected boolean isFirstHelloNegotiation = true;
-
+    private QueueKeeper<OfHeader, DataObject> queueKeeper;
+    private ExecutorService hsPool;
+    private HandshakeManager handshakeManager;
 
+    private boolean firstHelloProcessed;
+    
+    private PortFeaturesUtil portFeaturesUtils;
 
     /**
      * @param connectionAdapter
@@ -87,7 +93,13 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
     public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) {
         this.connectionAdapter = connectionAdapter;
         conductorState = CONDUCTOR_STATE.HANDSHAKING;
-        new Thread(new ErrorQueueHandler(errorQueue)).start();
+        hsPool = Executors.newFixedThreadPool(1);
+        firstHelloProcessed = false;
+        handshakeManager = new HandshakeManagerImpl(connectionAdapter,
+                ConnectionConductor.versionOrder.get(0), ConnectionConductor.versionOrder);
+        handshakeManager.setUseVersionBitmap(isBitmapNegotiationEnable);
+        handshakeManager.setHandshakeListener(this);
+        portFeaturesUtils = PortFeaturesUtil.getInstance();
     }
 
     @Override
@@ -97,32 +109,18 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
         connectionAdapter.setConnectionReadyListener(this);
     }
 
+    @Override
+    public void setQueueKeeper(QueueKeeper<OfHeader, DataObject> queueKeeper) {
+        this.queueKeeper = queueKeeper;
+    }
 
     /**
-     * send first hello message to switch
+     * @param errorHandler the errorHandler to set
      */
-    protected void sendFirstHelloMessage() {
-        Short highestVersion = ConnectionConductor.versionOrder.get(0);
-        Long helloXid = 21L;
-        HelloInput helloInput = null;
-        
-        if (isBitmapNegotiationEnable) {
-            helloInput = MessageFactory.createHelloInput(highestVersion, helloXid, ConnectionConductor.versionOrder);
-            LOG.debug("sending first hello message: vertsion header={} , version bitmap={}", 
-                    highestVersion, helloInput.getElements());
-        } else {
-            helloInput = MessageFactory.createHelloInput(highestVersion, helloXid);
-            LOG.debug("sending first hello message: version header={} ", highestVersion);
-        }
-        
-        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.");
-            handleException(e);
-        }
+    @Override
+    public void setErrorHandler(ErrorHandler errorHandler) {
+        this.errorHandler = errorHandler;
+        handshakeManager.setErrorHandler(errorHandler);
     }
 
     @Override
@@ -135,29 +133,25 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
                 builder.setVersion(echoRequestMessage.getVersion());
                 builder.setXid(echoRequestMessage.getXid());
                 builder.setData(echoRequestMessage.getData());
-                
-                connectionAdapter.echoReply(builder.build());
+
+                getConnectionAdapter().echoReply(builder.build());
             }
-        }).start();            
+        }).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, this);
     }
 
     @Override
     public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
-        LOG.debug("experimenter received, type: "
-                + experimenterMessage.getExpType());
-        notifyListeners(ExperimenterMessage.class, experimenterMessage);
+        queueKeeper.push(experimenterMessage, this);
     }
 
     @Override
     public void onFlowRemovedMessage(FlowRemovedMessage message) {
-        notifyListeners(FlowRemovedMessage.class, message);
+        queueKeeper.push(message, this);
     }
 
 
@@ -168,245 +162,127 @@ 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.
+     * 4. If Hello message received again with not supported version, just disconnect.
      *
      *   TODO: Better to handle handshake into a maintainable innerclass which uses State-Pattern.
      */
     @Override
-    public void onHelloMessage(final HelloMessage hello) {
-        // do handshake
-
-        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, elements);
-                try {
-                    // find the version from header version field
-                    proposedVersion = proposeVersion(remoteVersion);
-                    
-                } catch (IllegalArgumentException e) {
-                    handleException(e);
-                    connectionAdapter.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) {
-                        handleException(ex);
-                        connectionAdapter.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);
-                        connectionAdapter.disconnect();
-                    }
-                }
-            }
-        }).start();
-    }
-
-    /**
-     * send hello reply
-     * @param proposedVersion
-     * @param hello
-     */
-    protected void sendHelloReply(Short proposedVersion, Long xid)
-    {
-        HelloInput helloMsg = MessageFactory.createHelloInput(proposedVersion, xid);
-        RpcResult<Void> result;
-        try {
-            result = connectionAdapter.hello(helloMsg).get(getMaxTimeout(), getMaxTimeoutUnit());
-            smokeRpc(result);
-        } catch (Throwable e) {
-            handleException(e);
-        }
-    }
-
-
-    /**
-     * @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
-     */
-    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);
-        LOG.debug("sending feature request for version={} and xid={}", version, xid);
-        Future<RpcResult<GetFeaturesOutput>> featuresFuture = connectionAdapter
-                .getFeatures(featuresBuilder.build());
-        LOG.debug("waiting for features");
-        try {
-            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);
-            this.setListenerMapping(OFSessionUtil.getListenersMap());
-            LOG.info("handshake SETTLED: datapathId={}, auxiliaryId={}", featureOutput.getDatapathId(), featureOutput.getAuxiliaryId());
-        } catch (Throwable e) {
-            //handshake failed
-            LOG.error("issuing disconnect during handshake, reason: "+e.getMessage());
-            handleException(e);
-            disconnect();
-        }
+    public synchronized void onHelloMessage(final HelloMessage hello) {
+        LOG.debug("processing HELLO.xid: {}", hello.getXid());
+        firstHelloProcessed = true;
+        checkState(CONDUCTOR_STATE.HANDSHAKING);
+        HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
+                hello, handshakeManager, connectionAdapter);
+        hsPool.execute(handshakeStepWrapper);
     }
 
     /**
      * @return rpc-response timeout in [ms]
      */
-    private long getMaxTimeout() {
+    protected long getMaxTimeout() {
         // TODO:: get from configuration
         return 2000;
     }
-    
+
     /**
      * @return milliseconds
      */
-    private TimeUnit getMaxTimeoutUnit() {
+    protected TimeUnit getMaxTimeoutUnit() {
         // TODO:: get from configuration
         return TimeUnit.MILLISECONDS;
     }
 
-
-    /**
-     * @param e
-     */
-    protected void handleException(Throwable e) {
-        String sessionKeyId = null;
-        if (getSessionContext() != null) {
-            sessionKeyId = Arrays.toString(getSessionContext().getSessionKey().getId());
-        }
-        
-        Exception causeAndThread = new Exception(
-                "IN THREAD: "+Thread.currentThread().getName() +
-                "; session:"+sessionKeyId, e);
-        try {
-            errorQueue.put(causeAndThread);
-        } catch (InterruptedException e1) {
-            LOG.error(e1.getMessage(), e1);
-        }
-    }
-
-    @Override
-    public void onMultipartReplyMessage(MultipartReplyMessage arg0) {
-        // TODO Auto-generated method stub
-    }
-
     @Override
-    public void onMultipartRequestMessage(MultipartRequestMessage arg0) {
-        // TODO Auto-generated method stub
+    public void onMultipartReplyMessage(MultipartReplyMessage message) {
+        queueKeeper.push(message, this);
     }
 
     @Override
     public void onPacketInMessage(PacketInMessage message) {
-        notifyListeners(PacketInMessage.class, message);
+        queueKeeper.push(message, this, QueueKeeper.QueueType.UNORDERED);
     }
 
     @Override
     public void onPortStatusMessage(PortStatusMessage message) {
-        this.getSessionContext().processPortStatusMsg(message);
-        notifyListeners(PortStatusMessage.class, message);
+        processPortStatusMsg(message);
+        queueKeeper.push(message, this);
+    }
+    
+    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.warn("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(Port 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
-            disconnect();
-            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(getMaxTimeout(),
-                        getMaxTimeoutUnit());
-                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());
+                        errorHandler.handleException(e, sessionContext);
+                        //switch is not responding
+                        disconnect();
+                        OFSessionUtil.getSessionManager().invalidateOnDisconnect(ConnectionConductorImpl.this);
                     }
-                    //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(this);
             }
-        }
+
+        }).start();
     }
 
     /**
@@ -439,60 +315,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 : ConnectionConductor.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 : ConnectionConductor.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;
@@ -501,7 +323,7 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
     @Override
     public Future<Boolean> disconnect() {
         LOG.info("disconnecting: sessionCtx="+sessionContext+"|auxId="+auxiliaryKey);
-        
+
         Future<Boolean> result = null;
         if (connectionAdapter.isAlive()) {
             result = connectionAdapter.disconnect();
@@ -509,8 +331,8 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
             LOG.debug("connection already disconnected");
             result = Futures.immediateFuture(true);
         }
-        
-        return result; 
+
+        return result;
     }
 
     @Override
@@ -532,50 +354,102 @@ 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) {
-        this.listenerMapping = listenerMapping;
+
+    @Override
+    public ConnectionAdapter getConnectionAdapter() {
+        return connectionAdapter;
     }
 
-    /**
-     * @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);
-                    }
-                }
+    @Override
+    public synchronized 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.warn("No listeners for this message Type {}", messageType);
+            LOG.debug("already touched by hello message");
         }
     }
 
     @Override
-    public ConnectionAdapter getConnectionAdapter() {
-        return connectionAdapter;
+    public void onHandshakeSuccessfull(GetFeaturesOutput featureOutput,
+            Short negotiatedVersion) {
+        version = negotiatedVersion;
+        conductorState = CONDUCTOR_STATE.WORKING;
+        OFSessionUtil.registerSession(this, featureOutput, negotiatedVersion);
+        requestDesc();
+        requestPorts();
+        if(version == OFConstants.OFP_VERSION_1_3){
+            requestGroupFeatures();
+            requestMeterFeatures();
+        }
     }
 
-    @Override
-    public void onConnectionReady() {
-        LOG.debug("connection is ready-to-use");
-        //TODO: fire first helloMessage
-        new Thread(new Runnable() {
-            @Override
-            public void run() {
-                sendFirstHelloMessage();
-            }
-        }).start();
+    /*
+     *  Send an OFPMP_DESC request message to the switch
+     */
+
+    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 isBitmapNegotiationEnable the isBitmapNegotiationEnable to set
+     */
+    public void setBitmapNegotiationEnable(
+            boolean isBitmapNegotiationEnable) {
+        this.isBitmapNegotiationEnable = isBitmapNegotiationEnable;
+    }
+
+    protected void shutdownPool() {
+        hsPool.shutdownNow();
+        LOG.debug("pool is terminated: {}", hsPool.isTerminated());
     }
-    
 }