2 * Copyright (c) 2013 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 java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
13 import java.util.concurrent.Future;
14 import java.util.concurrent.TimeUnit;
16 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
17 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
18 import org.opendaylight.openflowplugin.openflow.md.OFConstants;
19 import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
20 import org.opendaylight.openflowplugin.openflow.md.core.session.PortFeaturesUtil;
21 import org.opendaylight.openflowplugin.openflow.md.core.session.SessionContext;
22 import org.opendaylight.openflowplugin.openflow.md.core.session.SessionManager;
23 import org.opendaylight.openflowplugin.openflow.md.queue.QueueKeeper;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInputBuilder;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInputBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Port;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestDescCaseBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestGroupFeaturesCaseBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestMeterFeaturesCaseBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestPortDescCaseBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
50 import org.opendaylight.yangtools.yang.binding.DataObject;
51 import org.opendaylight.yangtools.yang.common.RpcError;
52 import org.opendaylight.yangtools.yang.common.RpcResult;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 import com.google.common.util.concurrent.Futures;
61 public class ConnectionConductorImpl implements OpenflowProtocolListener,
62 SystemNotificationsListener, ConnectionConductor, ConnectionReadyListener, HandshakeListener {
64 protected static final Logger LOG = LoggerFactory
65 .getLogger(ConnectionConductorImpl.class);
67 /* variable to make BitMap-based negotiation enabled / disabled.
68 * it will help while testing and isolating issues related to processing of
69 * BitMaps from switches.
71 private boolean isBitmapNegotiationEnable = true;
72 protected ErrorHandler errorHandler;
74 private final ConnectionAdapter connectionAdapter;
75 private ConnectionConductor.CONDUCTOR_STATE conductorState;
76 private Short version;
78 private SwitchConnectionDistinguisher auxiliaryKey;
80 private SessionContext sessionContext;
82 private QueueKeeper<OfHeader, DataObject> queueKeeper;
83 private ExecutorService hsPool;
84 private HandshakeManager handshakeManager;
86 private boolean firstHelloProcessed;
88 private PortFeaturesUtil portFeaturesUtils;
91 * @param connectionAdapter
93 public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) {
94 this.connectionAdapter = connectionAdapter;
95 conductorState = CONDUCTOR_STATE.HANDSHAKING;
96 hsPool = Executors.newFixedThreadPool(1);
97 firstHelloProcessed = false;
98 handshakeManager = new HandshakeManagerImpl(connectionAdapter,
99 ConnectionConductor.versionOrder.get(0), ConnectionConductor.versionOrder);
100 handshakeManager.setUseVersionBitmap(isBitmapNegotiationEnable);
101 handshakeManager.setHandshakeListener(this);
102 portFeaturesUtils = PortFeaturesUtil.getInstance();
107 connectionAdapter.setMessageListener(this);
108 connectionAdapter.setSystemListener(this);
109 connectionAdapter.setConnectionReadyListener(this);
113 public void setQueueKeeper(QueueKeeper<OfHeader, DataObject> queueKeeper) {
114 this.queueKeeper = queueKeeper;
118 * @param errorHandler the errorHandler to set
121 public void setErrorHandler(ErrorHandler errorHandler) {
122 this.errorHandler = errorHandler;
123 handshakeManager.setErrorHandler(errorHandler);
127 public void onEchoRequestMessage(final EchoRequestMessage echoRequestMessage) {
128 new Thread(new Runnable() {
131 LOG.debug("echo request received: " + echoRequestMessage.getXid());
132 EchoReplyInputBuilder builder = new EchoReplyInputBuilder();
133 builder.setVersion(echoRequestMessage.getVersion());
134 builder.setXid(echoRequestMessage.getXid());
135 builder.setData(echoRequestMessage.getData());
137 getConnectionAdapter().echoReply(builder.build());
143 public void onErrorMessage(ErrorMessage errorMessage) {
144 queueKeeper.push(errorMessage, this);
148 public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
149 queueKeeper.push(experimenterMessage, this);
153 public void onFlowRemovedMessage(FlowRemovedMessage message) {
154 queueKeeper.push(message, this);
159 * version negotiation happened as per following steps:
160 * 1. If HelloMessage version field has same version, continue connection processing.
161 * If HelloMessage version is lower than supported versions, just disconnect.
162 * 2. If HelloMessage contains bitmap and common version found in bitmap
163 * then continue connection processing. if no common version found, just disconnect.
164 * 3. If HelloMessage version is not supported, send HelloMessage with lower supported version.
165 * 4. If Hello message received again with not supported version, just disconnect.
167 * TODO: Better to handle handshake into a maintainable innerclass which uses State-Pattern.
170 public synchronized void onHelloMessage(final HelloMessage hello) {
171 LOG.debug("processing HELLO.xid: {}", hello.getXid());
172 firstHelloProcessed = true;
173 checkState(CONDUCTOR_STATE.HANDSHAKING);
174 HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
175 hello, handshakeManager, connectionAdapter);
176 hsPool.execute(handshakeStepWrapper);
180 * @return rpc-response timeout in [ms]
182 protected long getMaxTimeout() {
183 // TODO:: get from configuration
188 * @return milliseconds
190 protected TimeUnit getMaxTimeoutUnit() {
191 // TODO:: get from configuration
192 return TimeUnit.MILLISECONDS;
196 public void onMultipartReplyMessage(MultipartReplyMessage message) {
197 queueKeeper.push(message, this);
201 public void onPacketInMessage(PacketInMessage message) {
202 queueKeeper.push(message, this, QueueKeeper.QueueType.UNORDERED);
206 public void onPortStatusMessage(PortStatusMessage message) {
207 processPortStatusMsg(message);
208 queueKeeper.push(message, this);
211 protected void processPortStatusMsg(PortStatus msg) {
212 if (msg.getReason().getIntValue() == 2) {
214 } else if (msg.getReason().getIntValue() == 0) {
216 } else if (msg.getReason().getIntValue() == 1) {
221 protected void updatePort(PortStatus msg) {
222 Long portNumber = msg.getPortNo();
223 Boolean portBandwidth = portFeaturesUtils.getPortBandwidth(msg);
225 if(portBandwidth == null) {
226 LOG.warn("can't get bandwidth info from port: {}, aborting port update", msg.toString());
228 this.getSessionContext().getPhysicalPorts().put(portNumber, msg);
229 this.getSessionContext().getPortsBandwidth().put(portNumber, portBandwidth);
233 protected void deletePort(Port port) {
234 Long portNumber = port.getPortNo();
236 this.getSessionContext().getPhysicalPorts().remove(portNumber);
237 this.getSessionContext().getPortsBandwidth().remove(portNumber);
241 public void onSwitchIdleEvent(SwitchIdleEvent notification) {
242 new Thread(new Runnable() {
245 if (!CONDUCTOR_STATE.WORKING.equals(getConductorState())) {
246 // idle state in any other conductorState than WORKING means real
247 // problem and wont be handled by echoReply, but disconnection
249 OFSessionUtil.getSessionManager().invalidateOnDisconnect(ConnectionConductorImpl.this);
251 LOG.debug("first idle state occured");
252 EchoInputBuilder builder = new EchoInputBuilder();
253 builder.setVersion(getVersion());
254 builder.setXid(getSessionContext().getNextXid());
256 Future<RpcResult<EchoOutput>> echoReplyFuture = getConnectionAdapter()
257 .echo(builder.build());
260 RpcResult<EchoOutput> echoReplyValue = echoReplyFuture.get(getMaxTimeout(),
261 getMaxTimeoutUnit());
262 if (echoReplyValue.isSuccessful()) {
263 setConductorState(CONDUCTOR_STATE.WORKING);
265 for (RpcError replyError : echoReplyValue.getErrors()) {
266 Throwable cause = replyError.getCause();
268 "while receiving echoReply in TIMEOUTING state: "
269 + cause.getMessage(), cause);
271 //switch issue occurred
272 throw new Exception("switch issue occurred");
274 } catch (Exception e) {
275 LOG.error("while waiting for echoReply in TIMEOUTING state: "
277 errorHandler.handleException(e, sessionContext);
278 //switch is not responding
280 OFSessionUtil.getSessionManager().invalidateOnDisconnect(ConnectionConductorImpl.this);
289 * @param conductorState
290 * the connectionState to set
293 public void setConductorState(CONDUCTOR_STATE conductorState) {
294 this.conductorState = conductorState;
298 public CONDUCTOR_STATE getConductorState() {
299 return conductorState;
305 protected void checkState(CONDUCTOR_STATE expectedState) {
306 if (!conductorState.equals(expectedState)) {
307 throw new IllegalStateException("Expected state: " + expectedState
308 + ", actual state:" + conductorState);
313 public void onDisconnectEvent(DisconnectEvent arg0) {
314 SessionManager sessionManager = OFSessionUtil.getSessionManager();
315 sessionManager.invalidateOnDisconnect(this);
319 public Short getVersion() {
324 public Future<Boolean> disconnect() {
325 LOG.info("disconnecting: sessionCtx="+sessionContext+"|auxId="+auxiliaryKey);
327 Future<Boolean> result = null;
328 if (connectionAdapter.isAlive()) {
329 result = connectionAdapter.disconnect();
331 LOG.debug("connection already disconnected");
332 result = Futures.immediateFuture(true);
339 public void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey) {
340 this.auxiliaryKey = auxiliaryKey;
344 public void setSessionContext(SessionContext sessionContext) {
345 this.sessionContext = sessionContext;
349 public SwitchConnectionDistinguisher getAuxiliaryKey() {
354 public SessionContext getSessionContext() {
355 return sessionContext;
359 public ConnectionAdapter getConnectionAdapter() {
360 return connectionAdapter;
364 public synchronized void onConnectionReady() {
365 LOG.debug("connection is ready-to-use");
366 if (! firstHelloProcessed) {
367 HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
368 null, handshakeManager, connectionAdapter);
369 hsPool.execute(handshakeStepWrapper);
370 firstHelloProcessed = true;
372 LOG.debug("already touched by hello message");
377 public void onHandshakeSuccessfull(GetFeaturesOutput featureOutput,
378 Short negotiatedVersion) {
379 version = negotiatedVersion;
380 conductorState = CONDUCTOR_STATE.WORKING;
381 OFSessionUtil.registerSession(this, featureOutput, negotiatedVersion);
384 if(version == OFConstants.OFP_VERSION_1_3){
385 requestGroupFeatures();
386 requestMeterFeatures();
391 * Send an OFPMP_DESC request message to the switch
394 private void requestDesc() {
395 MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder();
396 builder.setType(MultipartType.OFPMPDESC);
397 builder.setVersion(getVersion());
398 builder.setFlags(new MultipartRequestFlags(false));
399 builder.setMultipartRequestBody(new MultipartRequestDescCaseBuilder().build());
400 builder.setXid(getSessionContext().getNextXid());
401 getConnectionAdapter().multipartRequest(builder.build());
404 private void requestPorts() {
405 MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder();
406 builder.setType(MultipartType.OFPMPPORTDESC);
407 builder.setVersion(getVersion());
408 builder.setFlags(new MultipartRequestFlags(false));
409 builder.setMultipartRequestBody(new MultipartRequestPortDescCaseBuilder().build());
410 builder.setXid(getSessionContext().getNextXid());
411 getConnectionAdapter().multipartRequest(builder.build());
413 private void requestGroupFeatures(){
414 MultipartRequestInputBuilder mprInput = new MultipartRequestInputBuilder();
415 mprInput.setType(MultipartType.OFPMPGROUPFEATURES);
416 mprInput.setVersion(getVersion());
417 mprInput.setFlags(new MultipartRequestFlags(false));
418 mprInput.setXid(getSessionContext().getNextXid());
420 MultipartRequestGroupFeaturesCaseBuilder mprGroupFeaturesBuild =
421 new MultipartRequestGroupFeaturesCaseBuilder();
422 mprInput.setMultipartRequestBody(mprGroupFeaturesBuild.build());
424 LOG.debug("Send group features statistics request :{}",mprGroupFeaturesBuild);
425 getConnectionAdapter().multipartRequest(mprInput.build());
428 private void requestMeterFeatures(){
429 MultipartRequestInputBuilder mprInput = new MultipartRequestInputBuilder();
430 mprInput.setType(MultipartType.OFPMPMETERFEATURES);
431 mprInput.setVersion(getVersion());
432 mprInput.setFlags(new MultipartRequestFlags(false));
433 mprInput.setXid(getSessionContext().getNextXid());
435 MultipartRequestMeterFeaturesCaseBuilder mprMeterFeaturesBuild =
436 new MultipartRequestMeterFeaturesCaseBuilder();
437 mprInput.setMultipartRequestBody(mprMeterFeaturesBuild.build());
439 LOG.debug("Send meter features statistics request :{}",mprMeterFeaturesBuild);
440 getConnectionAdapter().multipartRequest(mprInput.build());
444 * @param isBitmapNegotiationEnable the isBitmapNegotiationEnable to set
446 public void setBitmapNegotiationEnable(
447 boolean isBitmapNegotiationEnable) {
448 this.isBitmapNegotiationEnable = isBitmapNegotiationEnable;
451 protected void shutdownPool() {
452 hsPool.shutdownNow();
453 LOG.debug("pool is terminated: {}", hsPool.isTerminated());