Merge "Quick fix RPCs and DevicCtx.close"
[openflowplugin.git] / openflowplugin / src / main / java / org / opendaylight / openflowplugin / openflow / md / core / ConnectionConductorImpl.java
index 902eb0e8a69a2e0c7afb9af7715d6e01c0a33b79..e9ad1e3d1ba04e4fb14cdaac51ce850ded1fe204 100644 (file)
@@ -1,5 +1,5 @@
 /**
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -8,17 +8,33 @@
 
 package org.opendaylight.openflowplugin.openflow.md.core;
 
-import java.util.Collection;
-import java.util.List;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.util.concurrent.Futures;
 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.openflowplugin.openflow.core.IMessageListener;
+import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
+import org.opendaylight.openflowplugin.api.OFConstants;
+import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext;
+import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
+import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
+import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener;
+import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeManager;
+import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer;
+import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;
+import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
+import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
+import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager;
+import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper;
+import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType;
+import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor;
+import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener;
+import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListenerImpl;
 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.openflowplugin.openflow.md.core.session.PortFeaturesUtil;
+import org.opendaylight.openflowplugin.openflow.md.queue.QueueKeeperFactory;
 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;
@@ -26,14 +42,14 @@ 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.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.system.rev130927.DisconnectEvent;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
@@ -44,213 +60,311 @@ 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;
-
 /**
  * @author mirehak
  */
 public class ConnectionConductorImpl implements OpenflowProtocolListener,
-        SystemNotificationsListener, ConnectionConductor {
+        SystemNotificationsListener, ConnectionConductor,
+        ConnectionReadyListener, HandshakeListener, NotificationEnqueuer,
+        AutoCloseable {
+
+    /**
+     * ingress queue limit
+     */
+    private static final int INGRESS_QUEUE_MAX_SIZE = 200;
 
-    private static final Logger LOG = LoggerFactory
+    protected static final Logger LOG = LoggerFactory
             .getLogger(ConnectionConductorImpl.class);
 
-    private LinkedBlockingQueue<Exception> errorQueue = new LinkedBlockingQueue<>();
+    /*
+     * variable to make BitMap-based negotiation enabled / disabled. it will
+     * help while testing and isolating issues related to processing of BitMaps
+     * from switches.
+     */
+    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;
+
+    protected SessionContext sessionContext;
+
+    private QueueProcessor<OfHeader, DataObject> queueProcessor;
+    private QueueKeeper<OfHeader> queue;
+    private ThreadPoolExecutor hsPool;
+    private HandshakeManager handshakeManager;
 
-    private SessionContext sessionContext;
+    private boolean firstHelloProcessed;
 
-    private ImmutableMap<Class<? extends DataObject>, Collection<IMessageListener>> listenerMapping;
+    private PortFeaturesUtil portFeaturesUtils;
+
+    private int conductorId;
+
+    private int ingressMaxQueueSize;
+    private HandshakeContext handshakeContext;
 
     /**
-     * @param connectionAdapter
+     * @param connectionAdapter connection adaptor for switch
      */
     public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) {
+        this(connectionAdapter, INGRESS_QUEUE_MAX_SIZE);
+    }
+
+    /**
+     * @param connectionAdapter connection adaptor for switch
+     * @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);
-        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);
+        connectionAdapter.setConnectionReadyListener(this);
+        WaterMarkListener waterMarkListener = new WaterMarkListenerImpl(
+                connectionAdapter);
+        queue = QueueKeeperFactory.createFairQueueKeeper(queueProcessor,
+                ingressMaxQueueSize, waterMarkListener);
     }
 
     @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());
+    public void setQueueProcessor(
+            QueueProcessor<OfHeader, DataObject> queueProcessor) {
+        this.queueProcessor = queueProcessor;
+    }
 
-        connectionAdapter.echoReply(builder.build());
+    /**
+     * @param errorHandler the errorHandler to set
+     */
+    @Override
+    public void setErrorHandler(ErrorHandler errorHandler) {
+        this.errorHandler = errorHandler;
+        handshakeManager.setErrorHandler(errorHandler);
+    }
+
+    @Override
+    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);
+    }
+
+    @Override
+    public void enqueueNotification(NotificationQueueWrapper notification) {
+        enqueueMessage(notification);
+    }
+
+    /**
+     * @param message
+     * @param queueType enqueue type
+     */
+    private void enqueueMessage(OfHeader message, QueueType queueType) {
+        queue.push(message, this, queueType);
     }
 
     @Override
     public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
-        // TODO Auto-generated method stub
-        LOG.debug("experimenter received, type: "
-                + experimenterMessage.getExpType());
+        enqueueMessage(experimenterMessage);
     }
 
     @Override
-    public void onFlowRemovedMessage(FlowRemovedMessage arg0) {
-        // TODO Auto-generated method stub
+    public void onFlowRemovedMessage(FlowRemovedMessage message) {
+        enqueueMessage(message);
     }
 
+    /**
+     * version negotiation happened as per following steps: 1. If HelloMessage
+     * version field has same version, continue connection processing. If
+     * HelloMessage version is lower than supported versions, just disconnect.
+     * 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. 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();
-        long xid = hello.getXid();
-        short proposedVersion;
-        try {
-            proposedVersion = proposeVersion(remoteVersion);
-        } catch (Exception e) {
-            handleException(e);
-            throw e;
-        }
-        HelloInputBuilder helloBuilder = new HelloInputBuilder();
-        xid++;
-        helloBuilder.setVersion(proposedVersion).setXid(xid);
-        LOG.debug("sending helloReply");
-        connectionAdapter.hello(helloBuilder.build());
-
-        if (proposedVersion != remoteVersion) {
-            // need to wait for another hello
-        } else {
-            // sent version is equal to remote --> version is negotiated
-            version = proposedVersion;
-            LOG.debug("version set: " + proposedVersion);
-
-            // request features
-            GetFeaturesInputBuilder featuresBuilder = new GetFeaturesInputBuilder();
-            xid++;
-            featuresBuilder.setVersion(version).setXid(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 {
-                    LOG.debug("obtained features: datapathId="
-                            + rpcFeatures.getResult().getDatapathId());
-                    conductorState = CONDUCTOR_STATE.WORKING;
-
-                    OFSessionUtil.registerSession(this,
-                            rpcFeatures.getResult(), version);
-                    LOG.info("handshake SETTLED");
-                }
-            } 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);
-        }
+    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) {
+        enqueueMessage(message);
     }
 
     @Override
-    public void onMultipartRequestMessage(MultipartRequestMessage arg0) {
-        // TODO Auto-generated method stub
+    public void onPacketInMessage(PacketInMessage message) {
+        enqueueMessage(message, QueueKeeper.QueueType.UNORDERED);
     }
 
     @Override
-    public void onPacketInMessage(PacketInMessage message) {
-        notifyListeners(PacketInMessage.class, message);
+    public void onPortStatusMessage(PortStatusMessage message) {
+        try {
+            processPortStatusMsg(message);
+        } finally {
+            enqueueMessage(message);
+        }
     }
 
-    @Override
-    public void onPortStatusMessage(PortStatusMessage arg0) {
-        // TODO Auto-generated method stub
+    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);
+        }
     }
 
-    @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);
+    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 {
-            LOG.debug("first idle state occured");
-            EchoInputBuilder builder = new EchoInputBuilder();
-            builder.setVersion(version);
-            // TODO: get xid from sessionContext
-            builder.setXid(42L);
+            if (null != this.sessionContext) {
+                //FIXME these two properties are never used in code
+                this.getSessionContext().getPhysicalPorts().put(portNumber, msg);
+                this.getSessionContext().getPortsBandwidth()
+                        .put(portNumber, portBandwidth);
+            } else {
+                LOG.warn("Trying to process update port message before session context was created.");
+            }
+        }
+    }
 
-            Future<RpcResult<EchoOutput>> echoReplyFuture = connectionAdapter
-                    .echo(builder.build());
+    protected void deletePort(PortGrouping port) {
+        Long portNumber = port.getPortNo();
 
-            try {
-                // TODO: read timeout from config
-                RpcResult<EchoOutput> echoReplyValue = echoReplyFuture.get(5,
-                        TimeUnit.SECONDS);
-                if (echoReplyValue.isSuccessful()) {
-                    conductorState = CONDUCTOR_STATE.WORKING;
+        this.getSessionContext().getPhysicalPorts().remove(portNumber);
+        this.getSessionContext().getPortsBandwidth().remove(portNumber);
+    }
+
+    @Override
+    public void onSwitchIdleEvent(SwitchIdleEvent notification) {
+        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();
     }
 
     /**
-     * @param conductorState
-     *            the connectionState to set
+     * @param conductorState the connectionState to set
      */
     @Override
     public void setConductorState(CONDUCTOR_STATE conductorState) {
@@ -263,10 +377,12 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
     }
 
     /**
-     * @param handshaking
+     * @param expectedState connection conductor state
      */
-    private void checkState(CONDUCTOR_STATE expectedState) {
+    protected void checkState(CONDUCTOR_STATE expectedState) {
         if (!conductorState.equals(expectedState)) {
+            LOG.warn("State of connection to switch {} is not correct, "
+                    + "terminating the connection", connectionAdapter.getRemoteAddress());
             throw new IllegalStateException("Expected state: " + expectedState
                     + ", actual state:" + conductorState);
         }
@@ -276,21 +392,7 @@ public class ConnectionConductorImpl implements OpenflowProtocolListener,
     public void onDisconnectEvent(DisconnectEvent arg0) {
         SessionManager sessionManager = OFSessionUtil.getSessionManager();
         sessionManager.invalidateOnDisconnect(this);
-    }
-
-    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;
+        close();
     }
 
     @Override
@@ -300,7 +402,18 @@ 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);
+        }
+        close();
+        return result;
     }
 
     @Override
@@ -323,26 +436,116 @@ 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) {
+            checkState(CONDUCTOR_STATE.HANDSHAKING);
+            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);
+    }
+
+    @Override
+    public void onHandshakeFailure() {
+        LOG.info("OF handshake failed, doing cleanup.");
+        close();
+    }
+
     /**
-     * @param listenerMapping the listenerMapping to set
+     * used by tests
+     *
+     * @param featureOutput feature request output
+     * @param negotiatedVersion negotiated openflow connection version
      */
-    public void setListenerMapping(
-            ImmutableMap<Class<? extends DataObject>, Collection<IMessageListener>> listenerMapping) {
-        //TODO: adjust the listener interface
-        this.listenerMapping = listenerMapping;
+    protected void postHandshakeBasic(GetFeaturesOutput featureOutput,
+                                      Short negotiatedVersion) {
+        version = negotiatedVersion;
+        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
+            //
+            // BUG-1988 - this must be the first item in queue in order not to
+            // get behind link-up message
+            enqueueMessage(featureOutput);
+        }
+
+        SessionContext sessionContext =  OFSessionUtil.registerSession(this, featureOutput, negotiatedVersion);
+        hsPool.shutdown();
+        hsPool.purge();
+        conductorState = CONDUCTOR_STATE.WORKING;
+        QueueKeeperFactory.plugQueue(queueProcessor, queue);
     }
 
     /**
-     * @param messageType
-     * @param message
+     * @param isBitmapNegotiationEnable the isBitmapNegotiationEnable to set
      */
-    private void notifyListeners(Class<? extends DataObject> messageType, DataObject message) {
-        Collection<IMessageListener> listeners = listenerMapping.get(messageType);
-        if (listeners != null) {
-            for (IMessageListener listener : listeners) {
-                //TODO: use some iface (message, conductor (connection+session id)
-                //listener.receive(someId, message);
+    public void setBitmapNegotiationEnable(boolean isBitmapNegotiationEnable) {
+        this.isBitmapNegotiationEnable = isBitmapNegotiationEnable;
+    }
+
+    @Override
+    public void setId(int conductorId) {
+        this.conductorId = conductorId;
+    }
+
+    @Override
+    public void close() {
+        conductorState = CONDUCTOR_STATE.RIP;
+        if (handshakeContext != null) {
+            try {
+                handshakeContext.close();
+            } catch (Exception e) {
+                LOG.warn("Closing handshake context failed: {}", e.getMessage());
+                LOG.debug("Detail in hanshake context close:", e);
+            }
+        } else {
+            //This condition will occure when Old Helium openflowplugin implementation will be used.
+            shutdownPoolPolitely();
+        }
+    }
+
+    private void shutdownPoolPolitely() {
+        LOG.debug("Terminating handshake pool for node {}", connectionAdapter.getRemoteAddress());
+        hsPool.shutdown();
+        try {
+            hsPool.awaitTermination(1, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
+            LOG.debug("Error while awaiting termination of pool. Will force shutdown now.");
+        } finally {
+            hsPool.purge();
+            if (!hsPool.isTerminated()) {
+                hsPool.shutdownNow();
             }
+            LOG.debug("is handshake pool for node {} is terminated : {}",
+                    connectionAdapter.getRemoteAddress(), hsPool.isTerminated());
         }
     }
+
+    @Override
+    public void setHandshakeContext(HandshakeContext handshakeContext) {
+        this.handshakeContext = handshakeContext;
+    }
+
+    @VisibleForTesting
+    ThreadPoolExecutor getHsPool() {
+        return hsPool;
+    }
 }