/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013-2014 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,
package org.opendaylight.openflowplugin.openflow.md.core;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
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.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.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.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.HelloElementType;
+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.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;
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.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;
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, NotificationEnqueuer,
+ AutoCloseable {
- 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.
+ /*
+ * 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 ImmutableMap<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);
+ WaterMarkListener waterMarkListener = new WaterMarkListenerImpl(
+ connectionAdapter);
+ queue = QueueKeeperFactory.createFairQueueKeeper(queueProcessor,
+ ingressMaxQueueSize, waterMarkListener);
}
+ @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);
}
- @Override
- public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
- // TODO Auto-generated method stub
- LOG.debug("experimenter received, type: "
- + experimenterMessage.getExpType());
+ /**
+ * @param message
+ */
+ private void enqueueMessage(OfHeader message) {
+ enqueueMessage(message, QueueType.DEFAULT);
}
@Override
- public void onFlowRemovedMessage(FlowRemovedMessage arg0) {
- // TODO Auto-generated method stub
+ public void enqueueNotification(NotificationQueueWrapper notification) {
+ enqueueMessage(notification);
}
-
/**
- * 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.
- * If Hello message received again with not supported version, just disconnect.
- *
- * TODO: Better to handle handshake into a maintainable innerclass which uses State-Pattern.
+ * @param message
+ * @param queueType
+ * enqueue type
*/
- @Override
- public void onHelloMessage(HelloMessage hello) {
- // do handshake
- LOG.info("handshake STARTED");
- checkState(CONDUCTOR_STATE.HANDSHAKING);
-
- Short remoteVersion = hello.getVersion();
- List<Elements> elements = hello.getElements();
- long xid = hello.getXid();
- short proposedVersion;
- LOG.debug("Hello message version={} and bitmap={}", remoteVersion, elements);
- try {
- // find the version from header version field
- proposedVersion = proposeVersion(remoteVersion);
-
- } catch (IllegalArgumentException e) {
- handleException(e);
- connectionAdapter.disconnect();
- throw e;
- }
-
- // sent version is equal to remote --> version is negotiated
- if (proposedVersion == remoteVersion) {
- LOG.debug("sending helloReply as version in header is supported: {}", proposedVersion);
- sendHelloReply(proposedVersion, ++xid);
- postHandshake(proposedVersion, ++xid);
-
- } else if (isBitmapNegotiationEnable && null != elements && 0 != elements.size()) {
- try {
- // hello contains version bitmap, checking highest common
- // version in bitmap
- proposedVersion = proposeBitmapVersion(elements);
- } catch (IllegalArgumentException ex) {
- handleException(ex);
- connectionAdapter.disconnect();
- throw ex;
- }
- LOG.debug("sending helloReply for common bitmap version : {}", proposedVersion);
- sendHelloReply(proposedVersion, ++xid);
- postHandshake(proposedVersion, ++xid);
- } else {
- if (isFirstHelloNegotiation) {
- isFirstHelloNegotiation = false;
- LOG.debug("sending helloReply for lowest supported version : {}", proposedVersion);
- // send hello reply with lower version number supported
- sendHelloReply(proposedVersion, ++xid);
- } else {
- // terminate the connection.
- LOG.debug("Version negotiation failed. unsupported version : {}", remoteVersion);
- connectionAdapter.disconnect();
- }
- }
+ private void enqueueMessage(OfHeader message, QueueType queueType) {
+ queue.push(message, this, queueType);
}
- /**
- * 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());
+ @Override
+ public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
+ enqueueMessage(experimenterMessage);
}
+ @Override
+ public void onFlowRemovedMessage(FlowRemovedMessage message) {
+ enqueueMessage(message);
+ }
/**
- * after handshake set features, register to session
- * @param proposedVersion
- * @param xId
+ * 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.
*/
- 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);
- }
+ @Override
+ public 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.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) {
+ 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);
+ }
}
- @Override
- public void onPortStatusMessage(PortStatusMessage arg0) {
- // TODO Auto-generated method stub
+ 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();
}
/**
}
/**
- * @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);
public void onDisconnectEvent(DisconnectEvent arg0) {
SessionManager sessionManager = OFSessionUtil.getSessionManager();
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;
+ close();
}
@Override
@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
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) {
+ requestPorts();
+ requestGroupFeatures();
+ requestMeterFeatures();
+ }
+
+ requestDesc();
+ }
+
+ @Override
+ public void onHandshakeFailure() {
+ LOG.info("OF handshake failed, doing cleanup.");
+ close();
+ }
+
/**
- * @param listenerMapping the listenerMapping to set
+ * used by tests
+ *
+ * @param featureOutput
+ * @param negotiatedVersion
+ */
+ 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);
+ }
+
+ OFSessionUtil.registerSession(this, featureOutput, negotiatedVersion);
+ hsPool.shutdown();
+ hsPool.purge();
+ conductorState = CONDUCTOR_STATE.WORKING;
+ QueueKeeperFactory.plugQueue(queueProcessor, queue);
+ }
+
+ /*
+ * Send an OFPMP_DESC request message to the switch
*/
- public void setListenerMapping(
- ImmutableMap<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) {
- //TODO : need to add unit-tests
- //listener.receive(this.getAuxiliaryKey(), this.getSessionContext(), message);
- }
+ public void setBitmapNegotiationEnable(boolean isBitmapNegotiationEnable) {
+ this.isBitmapNegotiationEnable = isBitmapNegotiationEnable;
+ }
+
+ protected void shutdownPool() {
+ hsPool.shutdownNow();
+ LOG.debug("pool is terminated: {}", hsPool.isTerminated());
+ }
+
+ protected void shutdownPoolPolitely() {
+ hsPool.shutdown();
+ try {
+ hsPool.awaitTermination(1, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ LOG.info("Error while awaiting termination on pool. Will use shutdownNow method.");
+ shutdownPool();
}
+ hsPool.purge();
+ LOG.debug("pool is terminated: {}", hsPool.isTerminated());
}
@Override
- public ConnectionAdapter getConnectionAdapter() {
- return connectionAdapter;
+ public void setId(int conductorId) {
+ this.conductorId = conductorId;
+ }
+
+ @Override
+ public void close() {
+ shutdownPoolPolitely();
+ conductorState = CONDUCTOR_STATE.RIP;
}
}