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