Merge "removing legacy listener on port 6633"
[openflowplugin.git] / openflowplugin / src / main / java / org / opendaylight / openflowplugin / openflow / md / core / ConnectionConductorImpl.java
1 /**
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.openflowplugin.openflow.md.core;
10
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
13 import java.util.concurrent.Future;
14 import java.util.concurrent.TimeUnit;
15
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.core.session.OFSessionUtil;
19 import org.opendaylight.openflowplugin.openflow.md.core.session.SessionContext;
20 import org.opendaylight.openflowplugin.openflow.md.core.session.SessionManager;
21 import org.opendaylight.openflowplugin.openflow.md.queue.QueueKeeper;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInputBuilder;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInputBuilder;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestDescBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestPortDescBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
44 import org.opendaylight.yangtools.yang.binding.DataObject;
45 import org.opendaylight.yangtools.yang.common.RpcError;
46 import org.opendaylight.yangtools.yang.common.RpcResult;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 import com.google.common.util.concurrent.Futures;
51
52 /**
53  * @author mirehak
54  */
55 public class ConnectionConductorImpl implements OpenflowProtocolListener,
56         SystemNotificationsListener, ConnectionConductor, ConnectionReadyListener, HandshakeListener {
57
58     protected static final Logger LOG = LoggerFactory
59             .getLogger(ConnectionConductorImpl.class);
60
61     /* variable to make BitMap-based negotiation enabled / disabled.
62      * it will help while testing and isolating issues related to processing of
63      * BitMaps from switches.
64      */
65     private boolean isBitmapNegotiationEnable = true;
66     protected ErrorHandler errorHandler;
67
68     private final ConnectionAdapter connectionAdapter;
69     private ConnectionConductor.CONDUCTOR_STATE conductorState;
70     private Short version;
71
72     private SwitchConnectionDistinguisher auxiliaryKey;
73
74     private SessionContext sessionContext;
75
76     private QueueKeeper<OfHeader, DataObject> queueKeeper;
77     private ExecutorService hsPool;
78     private HandshakeManager handshakeManager;
79
80     private boolean firstHelloProcessed;
81
82     /**
83      * @param connectionAdapter
84      */
85     public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) {
86         this.connectionAdapter = connectionAdapter;
87         conductorState = CONDUCTOR_STATE.HANDSHAKING;
88         hsPool = Executors.newFixedThreadPool(1);
89         firstHelloProcessed = false;
90         handshakeManager = new HandshakeManagerImpl(connectionAdapter,
91                 ConnectionConductor.versionOrder.get(0), ConnectionConductor.versionOrder);
92         handshakeManager.setUseVersionBitmap(isBitmapNegotiationEnable);
93         handshakeManager.setHandshakeListener(this);
94     }
95
96     @Override
97     public void init() {
98         connectionAdapter.setMessageListener(this);
99         connectionAdapter.setSystemListener(this);
100         connectionAdapter.setConnectionReadyListener(this);
101     }
102
103     @Override
104     public void setQueueKeeper(QueueKeeper<OfHeader, DataObject> queueKeeper) {
105         this.queueKeeper = queueKeeper;
106     }
107
108     /**
109      * @param errorHandler the errorHandler to set
110      */
111     @Override
112     public void setErrorHandler(ErrorHandler errorHandler) {
113         this.errorHandler = errorHandler;
114         handshakeManager.setErrorHandler(errorHandler);
115     }
116
117     @Override
118     public void onEchoRequestMessage(final EchoRequestMessage echoRequestMessage) {
119         new Thread(new Runnable() {
120             @Override
121             public void run() {
122                 LOG.debug("echo request received: " + echoRequestMessage.getXid());
123                 EchoReplyInputBuilder builder = new EchoReplyInputBuilder();
124                 builder.setVersion(echoRequestMessage.getVersion());
125                 builder.setXid(echoRequestMessage.getXid());
126                 builder.setData(echoRequestMessage.getData());
127
128                 getConnectionAdapter().echoReply(builder.build());
129             }
130         }).start();
131     }
132
133     @Override
134     public void onErrorMessage(ErrorMessage errorMessage) {
135         queueKeeper.push(errorMessage, this);
136     }
137
138     @Override
139     public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
140         queueKeeper.push(experimenterMessage, this);
141     }
142
143     @Override
144     public void onFlowRemovedMessage(FlowRemovedMessage message) {
145         queueKeeper.push(message, this);
146     }
147
148
149     /**
150      * version negotiation happened as per following steps:
151      * 1. If HelloMessage version field has same version, continue connection processing.
152      *    If HelloMessage version is lower than supported versions, just disconnect.
153      * 2. If HelloMessage contains bitmap and common version found in bitmap
154      *    then continue connection processing. if no common version found, just disconnect.
155      * 3. If HelloMessage version is not supported, send HelloMessage with lower supported version.
156      * 4. If Hello message received again with not supported version, just disconnect.
157      *
158      *   TODO: Better to handle handshake into a maintainable innerclass which uses State-Pattern.
159      */
160     @Override
161     public synchronized void onHelloMessage(final HelloMessage hello) {
162         LOG.debug("processing HELLO.xid{}", hello.getXid());
163         firstHelloProcessed = true;
164         checkState(CONDUCTOR_STATE.HANDSHAKING);
165         HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
166                 hello, handshakeManager, connectionAdapter);
167         hsPool.execute(handshakeStepWrapper);
168     }
169
170     /**
171      * @return rpc-response timeout in [ms]
172      */
173     protected long getMaxTimeout() {
174         // TODO:: get from configuration
175         return 2000;
176     }
177
178     /**
179      * @return milliseconds
180      */
181     protected TimeUnit getMaxTimeoutUnit() {
182         // TODO:: get from configuration
183         return TimeUnit.MILLISECONDS;
184     }
185
186     @Override
187     public void onMultipartReplyMessage(MultipartReplyMessage message) {
188         queueKeeper.push(message, this);
189     }
190
191     @Override
192     public void onPacketInMessage(PacketInMessage message) {
193         queueKeeper.push(message, this);
194     }
195
196     @Override
197     public void onPortStatusMessage(PortStatusMessage message) {
198         this.getSessionContext().processPortStatusMsg(message);
199         queueKeeper.push(message, this);
200     }
201
202     @Override
203     public void onSwitchIdleEvent(SwitchIdleEvent notification) {
204         new Thread(new Runnable() {
205             @Override
206             public void run() {
207                 if (!CONDUCTOR_STATE.WORKING.equals(getConductorState())) {
208                     // idle state in any other conductorState than WORKING means real
209                     // problem and wont be handled by echoReply, but disconnection
210                     disconnect();
211                     OFSessionUtil.getSessionManager().invalidateOnDisconnect(ConnectionConductorImpl.this);
212                 } else {
213                     LOG.debug("first idle state occured");
214                     EchoInputBuilder builder = new EchoInputBuilder();
215                     builder.setVersion(getVersion());
216                     builder.setXid(getSessionContext().getNextXid());
217
218                     Future<RpcResult<EchoOutput>> echoReplyFuture = getConnectionAdapter()
219                             .echo(builder.build());
220
221                     try {
222                         RpcResult<EchoOutput> echoReplyValue = echoReplyFuture.get(getMaxTimeout(),
223                                 getMaxTimeoutUnit());
224                         if (echoReplyValue.isSuccessful()) {
225                             setConductorState(CONDUCTOR_STATE.WORKING);
226                         } else {
227                             for (RpcError replyError : echoReplyValue.getErrors()) {
228                                 Throwable cause = replyError.getCause();
229                                 LOG.error(
230                                         "while receiving echoReply in TIMEOUTING state: "
231                                                 + cause.getMessage(), cause);
232                             }
233                             //switch issue occurred
234                             throw new Exception("switch issue occurred");
235                         }
236                     } catch (Exception e) {
237                         LOG.error("while waiting for echoReply in TIMEOUTING state: "
238                                 + e.getMessage());
239                         errorHandler.handleException(e, sessionContext);
240                         //switch is not responding
241                         disconnect();
242                         OFSessionUtil.getSessionManager().invalidateOnDisconnect(ConnectionConductorImpl.this);
243                     }
244                 }
245             }
246
247         }).start();
248     }
249
250     /**
251      * @param conductorState
252      *            the connectionState to set
253      */
254     @Override
255     public void setConductorState(CONDUCTOR_STATE conductorState) {
256         this.conductorState = conductorState;
257     }
258
259     @Override
260     public CONDUCTOR_STATE getConductorState() {
261         return conductorState;
262     }
263
264     /**
265      * @param handshaking
266      */
267     protected void checkState(CONDUCTOR_STATE expectedState) {
268         if (!conductorState.equals(expectedState)) {
269             throw new IllegalStateException("Expected state: " + expectedState
270                     + ", actual state:" + conductorState);
271         }
272     }
273
274     @Override
275     public void onDisconnectEvent(DisconnectEvent arg0) {
276         SessionManager sessionManager = OFSessionUtil.getSessionManager();
277         sessionManager.invalidateOnDisconnect(this);
278     }
279
280     @Override
281     public Short getVersion() {
282         return version;
283     }
284
285     @Override
286     public Future<Boolean> disconnect() {
287         LOG.info("disconnecting: sessionCtx="+sessionContext+"|auxId="+auxiliaryKey);
288
289         Future<Boolean> result = null;
290         if (connectionAdapter.isAlive()) {
291             result = connectionAdapter.disconnect();
292         } else {
293             LOG.debug("connection already disconnected");
294             result = Futures.immediateFuture(true);
295         }
296
297         return result;
298     }
299
300     @Override
301     public void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey) {
302         this.auxiliaryKey = auxiliaryKey;
303     }
304
305     @Override
306     public void setSessionContext(SessionContext sessionContext) {
307         this.sessionContext = sessionContext;
308     }
309
310     @Override
311     public SwitchConnectionDistinguisher getAuxiliaryKey() {
312         return auxiliaryKey;
313     }
314
315     @Override
316     public SessionContext getSessionContext() {
317         return sessionContext;
318     }
319
320     @Override
321     public ConnectionAdapter getConnectionAdapter() {
322         return connectionAdapter;
323     }
324
325     @Override
326     public synchronized void onConnectionReady() {
327         LOG.debug("connection is ready-to-use");
328         if (! firstHelloProcessed) {
329             HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
330                     null, handshakeManager, connectionAdapter);
331             hsPool.execute(handshakeStepWrapper);
332             firstHelloProcessed = true;
333         } else {
334             LOG.debug("already touched by hello message");
335         }
336     }
337
338     @Override
339     public void onHandshakeSuccessfull(GetFeaturesOutput featureOutput,
340             Short negotiatedVersion) {
341         version = negotiatedVersion;
342         conductorState = CONDUCTOR_STATE.WORKING;
343         OFSessionUtil.registerSession(this, featureOutput, negotiatedVersion);
344         requestDesc();
345         requestPorts();
346     }
347
348     /*
349      *  Send an OFPMP_DESC request message to the switch
350      */
351
352     private void requestDesc() {
353         MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder();
354         builder.setType(MultipartType.OFPMPDESC);
355         builder.setVersion(getVersion());
356         builder.setFlags(new MultipartRequestFlags(false));
357         builder.setMultipartRequestBody(new MultipartRequestDescBuilder().build());
358         builder.setXid(getSessionContext().getNextXid());
359         getConnectionAdapter().multipartRequest(builder.build());
360     }
361
362     private void requestPorts() {
363         MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder();
364         builder.setType(MultipartType.OFPMPPORTDESC);
365         builder.setVersion(getVersion());
366         builder.setFlags(new MultipartRequestFlags(false));
367         builder.setMultipartRequestBody(new MultipartRequestPortDescBuilder().build());
368         builder.setXid(getSessionContext().getNextXid());
369         getConnectionAdapter().multipartRequest(builder.build());
370     }
371
372     /**
373      * @param isBitmapNegotiationEnable the isBitmapNegotiationEnable to set
374      */
375     public void setBitmapNegotiationEnable(
376             boolean isBitmapNegotiationEnable) {
377         this.isBitmapNegotiationEnable = isBitmapNegotiationEnable;
378     }
379
380     protected void shutdownPool() {
381         hsPool.shutdownNow();
382         LOG.debug("pool is terminated: {}", hsPool.isTerminated());
383     }
384 }