added disconnect delegator to conductor, session invalidation
[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.List;
12 import java.util.concurrent.Future;
13 import java.util.concurrent.LinkedBlockingQueue;
14 import java.util.concurrent.TimeUnit;
15
16 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
17 import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
18 import org.opendaylight.openflowplugin.openflow.md.core.session.SessionContext;
19 import org.opendaylight.openflowplugin.openflow.md.core.session.SessionManager;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInputBuilder;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInputBuilder;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInputBuilder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInputBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestMessage;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
39 import org.opendaylight.yangtools.yang.common.RpcError;
40 import org.opendaylight.yangtools.yang.common.RpcResult;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import com.google.common.collect.Lists;
45
46 /**
47  * @author mirehak
48  */
49 public class ConnectionConductorImpl implements OpenflowProtocolListener,
50         SystemNotificationsListener, ConnectionConductor {
51
52     private static final Logger LOG = LoggerFactory
53             .getLogger(ConnectionConductorImpl.class);
54
55     private LinkedBlockingQueue<Exception> errorQueue = new LinkedBlockingQueue<>();
56
57     private final ConnectionAdapter connectionAdapter;
58     private final List<Short> versionOrder;
59     private ConnectionConductor.CONDUCTOR_STATE conductorState;
60     private Short version;
61
62     private SwitchConnectionDistinguisher auxiliaryKey;
63
64     private SessionContext sessionContext;
65
66     /**
67      * @param connectionAdapter
68      */
69     public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) {
70         this.connectionAdapter = connectionAdapter;
71         conductorState = CONDUCTOR_STATE.HANDSHAKING;
72         versionOrder = Lists.newArrayList((short) 0x04, (short) 0x01);
73         new Thread(new ErrorQueueHandler(errorQueue)).start();
74     }
75
76     @Override
77     public void init() {
78         connectionAdapter.setMessageListener(this);
79         connectionAdapter.setSystemListener(this);
80     }
81
82     @Override
83     public void onEchoRequestMessage(EchoRequestMessage echoRequestMessage) {
84         LOG.debug("echo request received: " + echoRequestMessage.getXid());
85         EchoReplyInputBuilder builder = new EchoReplyInputBuilder();
86         builder.setVersion(echoRequestMessage.getVersion());
87         builder.setXid(echoRequestMessage.getXid());
88         builder.setData(echoRequestMessage.getData());
89
90         connectionAdapter.echoReply(builder.build());
91     }
92
93     @Override
94     public void onErrorMessage(ErrorMessage errorMessage) {
95         // TODO Auto-generated method stub
96         LOG.debug("error received, type: " + errorMessage.getType()
97                 + "; code: " + errorMessage.getCode());
98     }
99
100     @Override
101     public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
102         // TODO Auto-generated method stub
103         LOG.debug("experimenter received, type: "
104                 + experimenterMessage.getExpType());
105     }
106
107     @Override
108     public void onFlowRemovedMessage(FlowRemovedMessage arg0) {
109         // TODO Auto-generated method stub
110     }
111
112     @Override
113     public void onHelloMessage(HelloMessage hello) {
114         // do handshake
115         LOG.info("handshake STARTED");
116         checkState(CONDUCTOR_STATE.HANDSHAKING);
117
118         Short remoteVersion = hello.getVersion();
119         short proposedVersion;
120         try {
121             proposedVersion = proposeVersion(remoteVersion);
122         } catch (Exception e) {
123             handleException(e);
124             throw e;
125         }
126         HelloInputBuilder helloBuilder = new HelloInputBuilder();
127         helloBuilder.setVersion(proposedVersion).setXid(hello.getXid());
128         LOG.debug("sending helloReply");
129         connectionAdapter.hello(helloBuilder.build());
130
131         if (proposedVersion != remoteVersion) {
132             // need to wait for another hello
133         } else {
134             // sent version is equal to remote --> version is negotiated
135             version = proposedVersion;
136             LOG.debug("version set: " + proposedVersion);
137
138             // request features
139             GetFeaturesInputBuilder featuresBuilder = new GetFeaturesInputBuilder();
140             featuresBuilder.setVersion(version).setXid(hello.getXid());
141             Future<RpcResult<GetFeaturesOutput>> featuresFuture = connectionAdapter
142                     .getFeatures(featuresBuilder.build());
143             LOG.debug("waiting for features");
144             RpcResult<GetFeaturesOutput> rpcFeatures;
145             try {
146                 rpcFeatures = featuresFuture.get(getMaxTimeout(),
147                         TimeUnit.MILLISECONDS);
148                 if (!rpcFeatures.isSuccessful()) {
149                     LOG.error("obtained features problem: "
150                             + rpcFeatures.getErrors());
151                 } else {
152                     LOG.debug("obtained features: datapathId="
153                             + rpcFeatures.getResult().getDatapathId());
154                     conductorState = CONDUCTOR_STATE.WORKING;
155
156                     OFSessionUtil.registerSession(this,
157                             rpcFeatures.getResult(), version);
158                     LOG.info("handshake SETTLED");
159                 }
160             } catch (Exception e) {
161                 handleException(e);
162             }
163         }
164     }
165
166     /**
167      * @return rpc-response timeout in [ms]
168      */
169     private long getMaxTimeout() {
170         // TODO:: get from configuration
171         return 2000;
172     }
173
174     /**
175      * @param e
176      */
177     private void handleException(Exception e) {
178         try {
179             errorQueue.put(e);
180         } catch (InterruptedException e1) {
181             LOG.error(e1.getMessage(), e1);
182         }
183     }
184
185     @Override
186     public void onMultipartReplyMessage(MultipartReplyMessage arg0) {
187         // TODO Auto-generated method stub
188     }
189
190     @Override
191     public void onMultipartRequestMessage(MultipartRequestMessage arg0) {
192         // TODO Auto-generated method stub
193     }
194
195     @Override
196     public void onPacketInMessage(PacketInMessage arg0) {
197         // TODO Auto-generated method stub
198     }
199
200     @Override
201     public void onPortStatusMessage(PortStatusMessage arg0) {
202         // TODO Auto-generated method stub
203     }
204
205     @Override
206     public void onSwitchIdleEvent(SwitchIdleEvent notification) {
207         if (!CONDUCTOR_STATE.WORKING.equals(conductorState)) {
208             // idle state in any other conductorState than WORKING means real
209             // problem and wont
210             // be handled by echoReply
211             // TODO: invalidate this connection + notify
212         } else {
213             LOG.debug("first idle state occured");
214             EchoInputBuilder builder = new EchoInputBuilder();
215             builder.setVersion(version);
216             // TODO: get xid from sessionContext
217             builder.setXid(42L);
218
219             Future<RpcResult<EchoOutput>> echoReplyFuture = connectionAdapter
220                     .echo(builder.build());
221
222             try {
223                 // TODO: read timeout from config
224                 RpcResult<EchoOutput> echoReplyValue = echoReplyFuture.get(5,
225                         TimeUnit.SECONDS);
226                 if (echoReplyValue.isSuccessful()) {
227                     conductorState = CONDUCTOR_STATE.WORKING;
228                 } else {
229                     for (RpcError replyError : echoReplyValue.getErrors()) {
230                         Throwable cause = replyError.getCause();
231                         LOG.error(
232                                 "while receiving echoReply in TIMEOUTING state: "
233                                         + cause.getMessage(), cause);
234                     }
235                 }
236             } catch (Exception e) {
237                 LOG.error("while waiting for echoReply in TIMEOUTING state: "
238                         + e.getMessage(), e);
239             }
240         }
241     }
242
243     /**
244      * @param conductorState
245      *            the connectionState to set
246      */
247     @Override
248     public void setConductorState(CONDUCTOR_STATE conductorState) {
249         this.conductorState = conductorState;
250     }
251
252     @Override
253     public CONDUCTOR_STATE getConductorState() {
254         return conductorState;
255     }
256
257     /**
258      * @param handshaking
259      */
260     private void checkState(CONDUCTOR_STATE expectedState) {
261         if (!conductorState.equals(expectedState)) {
262             throw new IllegalStateException("Expected state: " + expectedState
263                     + ", actual state:" + conductorState);
264         }
265     }
266
267     @Override
268     public void onDisconnectEvent(DisconnectEvent arg0) {
269         SessionManager sessionManager = OFSessionUtil.getSessionManager();
270         sessionManager.invalidateOnDisconnect(this);
271     }
272
273     protected short proposeVersion(short remoteVersion) {
274         Short proposal = null;
275         for (short offer : versionOrder) {
276             if (offer <= remoteVersion) {
277                 proposal = offer;
278                 break;
279             }
280         }
281         if (proposal == null) {
282             throw new IllegalArgumentException("unsupported version: "
283                     + remoteVersion);
284         }
285         return proposal;
286     }
287
288     @Override
289     public Short getVersion() {
290         return version;
291     }
292
293     @Override
294     public Future<Boolean> disconnect() {
295         return connectionAdapter.disconnect();
296     }
297
298     @Override
299     public void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey) {
300         this.auxiliaryKey = auxiliaryKey;
301     }
302
303     @Override
304     public void setSessionContext(SessionContext sessionContext) {
305         this.sessionContext = sessionContext;
306     }
307
308     @Override
309     public SwitchConnectionDistinguisher getAuxiliaryKey() {
310         return auxiliaryKey;
311     }
312
313     @Override
314     public SessionContext getSessionContext() {
315         return sessionContext;
316     }
317 }