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