2 * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.openflowplugin.openflow.md.core;
11 import com.google.common.util.concurrent.Futures;
12 import java.util.concurrent.Future;
13 import java.util.concurrent.TimeUnit;
14 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
15 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
16 import org.opendaylight.openflowplugin.api.OFConstants;
17 import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext;
18 import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
19 import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
20 import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener;
21 import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeManager;
22 import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer;
23 import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;
24 import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
25 import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
26 import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager;
27 import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper;
28 import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType;
29 import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor;
30 import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener;
31 import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListenerImpl;
32 import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
33 import org.opendaylight.openflowplugin.openflow.md.core.session.PortFeaturesUtil;
34 import org.opendaylight.openflowplugin.openflow.md.queue.QueueKeeperFactory;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInputBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInputBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
54 import org.opendaylight.yangtools.yang.binding.DataObject;
55 import org.opendaylight.yangtools.yang.common.RpcError;
56 import org.opendaylight.yangtools.yang.common.RpcResult;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
63 public class ConnectionConductorImpl implements OpenflowProtocolListener,
64 SystemNotificationsListener, ConnectionConductor,
65 ConnectionReadyListener, HandshakeListener, NotificationEnqueuer,
71 private static final int INGRESS_QUEUE_MAX_SIZE = 200;
73 protected static final Logger LOG = LoggerFactory
74 .getLogger(ConnectionConductorImpl.class);
77 * variable to make BitMap-based negotiation enabled / disabled. it will
78 * help while testing and isolating issues related to processing of BitMaps
81 private boolean isBitmapNegotiationEnable = true;
82 protected ErrorHandler errorHandler;
84 private final ConnectionAdapter connectionAdapter;
85 private ConnectionConductor.CONDUCTOR_STATE conductorState;
86 private Short version;
88 protected SwitchConnectionDistinguisher auxiliaryKey;
90 protected SessionContext sessionContext;
92 private QueueProcessor<OfHeader, DataObject> queueProcessor;
93 private QueueKeeper<OfHeader> queue;
94 private HandshakeManager handshakeManager;
96 private boolean firstHelloProcessed;
98 private PortFeaturesUtil portFeaturesUtils;
100 private int conductorId;
102 private int ingressMaxQueueSize;
103 private HandshakeContext handshakeContext;
106 * @param connectionAdapter connection adaptor for switch
108 public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) {
109 this(connectionAdapter, INGRESS_QUEUE_MAX_SIZE);
113 * @param connectionAdapter connection adaptor for switch
114 * @param ingressMaxQueueSize ingress queue limit (blocking)
116 public ConnectionConductorImpl(ConnectionAdapter connectionAdapter,
117 int ingressMaxQueueSize) {
118 this.connectionAdapter = connectionAdapter;
119 this.ingressMaxQueueSize = ingressMaxQueueSize;
120 conductorState = CONDUCTOR_STATE.HANDSHAKING;
121 firstHelloProcessed = false;
122 handshakeManager = new HandshakeManagerImpl(connectionAdapter,
123 ConnectionConductor.VERSION_ORDER.get(0),
124 ConnectionConductor.VERSION_ORDER);
125 handshakeManager.setUseVersionBitmap(isBitmapNegotiationEnable);
126 handshakeManager.setHandshakeListener(this);
127 portFeaturesUtils = PortFeaturesUtil.getInstance();
132 connectionAdapter.setMessageListener(this);
133 connectionAdapter.setSystemListener(this);
134 connectionAdapter.setConnectionReadyListener(this);
135 WaterMarkListener waterMarkListener = new WaterMarkListenerImpl(
137 queue = QueueKeeperFactory.createFairQueueKeeper(queueProcessor,
138 ingressMaxQueueSize, waterMarkListener);
142 public void setQueueProcessor(
143 QueueProcessor<OfHeader, DataObject> queueProcessor) {
144 this.queueProcessor = queueProcessor;
148 * @param errorHandler the errorHandler to set
151 public void setErrorHandler(ErrorHandler errorHandler) {
152 this.errorHandler = errorHandler;
153 handshakeManager.setErrorHandler(errorHandler);
157 public void onEchoRequestMessage(final EchoRequestMessage echoRequestMessage) {
158 new Thread(new Runnable() {
161 LOG.debug("echo request received: "
162 + echoRequestMessage.getXid());
163 EchoReplyInputBuilder builder = new EchoReplyInputBuilder();
164 builder.setVersion(echoRequestMessage.getVersion());
165 builder.setXid(echoRequestMessage.getXid());
166 builder.setData(echoRequestMessage.getData());
168 getConnectionAdapter().echoReply(builder.build());
174 public void onErrorMessage(ErrorMessage errorMessage) {
175 enqueueMessage(errorMessage);
181 private void enqueueMessage(OfHeader message) {
182 enqueueMessage(message, QueueType.DEFAULT);
186 public void enqueueNotification(NotificationQueueWrapper notification) {
187 enqueueMessage(notification);
192 * @param queueType enqueue type
194 private void enqueueMessage(OfHeader message, QueueType queueType) {
195 queue.push(message, this, queueType);
199 public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
200 enqueueMessage(experimenterMessage);
204 public void onFlowRemovedMessage(FlowRemovedMessage message) {
205 enqueueMessage(message);
209 * version negotiation happened as per following steps: 1. If HelloMessage
210 * version field has same version, continue connection processing. If
211 * HelloMessage version is lower than supported versions, just disconnect.
212 * 2. If HelloMessage contains bitmap and common version found in bitmap
213 * then continue connection processing. if no common version found, just
214 * disconnect. 3. If HelloMessage version is not supported, send
215 * HelloMessage with lower supported version. 4. If Hello message received
216 * again with not supported version, just disconnect.
219 public void onHelloMessage(final HelloMessage hello) {
220 LOG.debug("processing HELLO.xid: {}", hello.getXid());
221 firstHelloProcessed = true;
222 checkState(CONDUCTOR_STATE.HANDSHAKING);
223 HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
224 hello, handshakeManager, connectionAdapter);
225 Thread t = new Thread(handshakeStepWrapper, "OFHandshake-" + conductorId);
231 * @return rpc-response timeout in [ms]
233 protected long getMaxTimeout() {
234 // TODO:: get from configuration
239 * @return milliseconds
241 protected TimeUnit getMaxTimeoutUnit() {
242 // TODO:: get from configuration
243 return TimeUnit.MILLISECONDS;
247 public void onMultipartReplyMessage(MultipartReplyMessage message) {
248 enqueueMessage(message);
252 public void onPacketInMessage(PacketInMessage message) {
253 enqueueMessage(message, QueueKeeper.QueueType.UNORDERED);
257 public void onPortStatusMessage(PortStatusMessage message) {
259 processPortStatusMsg(message);
261 enqueueMessage(message);
265 protected void processPortStatusMsg(PortStatus msg) {
266 if (msg.getReason().getIntValue() == 2) {
268 } else if (msg.getReason().getIntValue() == 0) {
270 } else if (msg.getReason().getIntValue() == 1) {
275 protected void updatePort(PortStatus msg) {
276 Long portNumber = msg.getPortNo();
277 Boolean portBandwidth = portFeaturesUtils.getPortBandwidth(msg);
279 if (portBandwidth == null) {
281 "can't get bandwidth info from port: {}, aborting port update",
284 if (null != this.sessionContext) {
285 //FIXME these two properties are never used in code
286 this.getSessionContext().getPhysicalPorts().put(portNumber, msg);
287 this.getSessionContext().getPortsBandwidth()
288 .put(portNumber, portBandwidth);
290 LOG.warn("Trying to process update port message before session context was created.");
295 protected void deletePort(PortGrouping port) {
296 Long portNumber = port.getPortNo();
298 this.getSessionContext().getPhysicalPorts().remove(portNumber);
299 this.getSessionContext().getPortsBandwidth().remove(portNumber);
303 public void onSwitchIdleEvent(SwitchIdleEvent notification) {
304 new Thread(new Runnable() {
307 if (!CONDUCTOR_STATE.WORKING.equals(getConductorState())) {
308 // idle state in any other conductorState than WORKING means
310 // problem and wont be handled by echoReply, but
313 OFSessionUtil.getSessionManager().invalidateOnDisconnect(
314 ConnectionConductorImpl.this);
317 "first idle state occured, sessionCtx={}|auxId={}",
318 sessionContext, auxiliaryKey);
319 EchoInputBuilder builder = new EchoInputBuilder();
320 builder.setVersion(getVersion());
321 builder.setXid(getSessionContext().getNextXid());
323 Future<RpcResult<EchoOutput>> echoReplyFuture = getConnectionAdapter()
324 .echo(builder.build());
327 RpcResult<EchoOutput> echoReplyValue = echoReplyFuture
328 .get(getMaxTimeout(), getMaxTimeoutUnit());
329 if (echoReplyValue.isSuccessful()) {
330 setConductorState(CONDUCTOR_STATE.WORKING);
332 for (RpcError replyError : echoReplyValue
334 Throwable cause = replyError.getCause();
336 "while receiving echoReply in TIMEOUTING state: "
337 + cause.getMessage(), cause);
339 // switch issue occurred
340 throw new Exception("switch issue occurred");
342 } catch (Exception e) {
343 LOG.error("while waiting for echoReply in TIMEOUTING state: "
345 errorHandler.handleException(e, sessionContext);
346 // switch is not responding
348 OFSessionUtil.getSessionManager()
349 .invalidateOnDisconnect(
350 ConnectionConductorImpl.this);
359 * @param conductorState the connectionState to set
362 public void setConductorState(CONDUCTOR_STATE conductorState) {
363 this.conductorState = conductorState;
367 public CONDUCTOR_STATE getConductorState() {
368 return conductorState;
372 * @param expectedState connection conductor state
374 protected void checkState(CONDUCTOR_STATE expectedState) {
375 if (!conductorState.equals(expectedState)) {
376 LOG.warn("State of connection to switch {} is not correct, "
377 + "terminating the connection", connectionAdapter.getRemoteAddress());
378 throw new IllegalStateException("Expected state: " + expectedState
379 + ", actual state:" + conductorState);
384 public void onDisconnectEvent(DisconnectEvent arg0) {
385 SessionManager sessionManager = OFSessionUtil.getSessionManager();
386 sessionManager.invalidateOnDisconnect(this);
391 public Short getVersion() {
396 public Future<Boolean> disconnect() {
397 LOG.trace("disconnecting: sessionCtx={}|auxId={}", sessionContext,
400 Future<Boolean> result = null;
401 if (connectionAdapter.isAlive()) {
402 result = connectionAdapter.disconnect();
404 LOG.debug("connection already disconnected");
405 result = Futures.immediateFuture(true);
412 public void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey) {
413 this.auxiliaryKey = auxiliaryKey;
417 public void setSessionContext(SessionContext sessionContext) {
418 this.sessionContext = sessionContext;
422 public SwitchConnectionDistinguisher getAuxiliaryKey() {
427 public SessionContext getSessionContext() {
428 return sessionContext;
432 public ConnectionAdapter getConnectionAdapter() {
433 return connectionAdapter;
437 public void onConnectionReady() {
438 LOG.debug("connection is ready-to-use");
439 if (!firstHelloProcessed) {
440 checkState(CONDUCTOR_STATE.HANDSHAKING);
441 HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
442 null, handshakeManager, connectionAdapter);
443 Thread t = new Thread(handshakeStepWrapper, "OFHandshake-" + conductorId);
446 firstHelloProcessed = true;
448 LOG.debug("already touched by hello message");
453 public void onHandshakeSuccessful(GetFeaturesOutput featureOutput,
454 Short negotiatedVersion) {
455 postHandshakeBasic(featureOutput, negotiatedVersion);
459 public void onHandshakeFailure() {
460 LOG.info("OF handshake failed, doing cleanup.");
467 * @param featureOutput feature request output
468 * @param negotiatedVersion negotiated openflow connection version
470 protected void postHandshakeBasic(GetFeaturesOutput featureOutput,
471 Short negotiatedVersion) {
472 version = negotiatedVersion;
473 if (version == OFConstants.OFP_VERSION_1_0) {
474 // Because the GetFeaturesOutput contains information about the port
475 // in OF1.0 (that we would otherwise get from the PortDesc) we have
477 // it up for parsing to convert into a NodeConnectorUpdate
479 // BUG-1988 - this must be the first item in queue in order not to
480 // get behind link-up message
481 enqueueMessage(featureOutput);
484 SessionContext sessionContext = OFSessionUtil.registerSession(this, featureOutput, negotiatedVersion);
485 conductorState = CONDUCTOR_STATE.WORKING;
486 QueueKeeperFactory.plugQueue(queueProcessor, queue);
490 * @param isBitmapNegotiationEnable the isBitmapNegotiationEnable to set
492 public void setBitmapNegotiationEnable(boolean isBitmapNegotiationEnable) {
493 this.isBitmapNegotiationEnable = isBitmapNegotiationEnable;
497 public void setId(int conductorId) {
498 this.conductorId = conductorId;
502 public void close() {
503 conductorState = CONDUCTOR_STATE.RIP;
504 if (handshakeContext != null) {
506 handshakeContext.close();
507 } catch (Exception e) {
508 LOG.warn("Closing handshake context failed: {}", e.getMessage());
509 LOG.debug("Detail in hanshake context close:", e);
515 public void setHandshakeContext(HandshakeContext handshakeContext) {
516 this.handshakeContext = handshakeContext;