d2c8f1be4278590ea18de8b3b1c9d0d33e174e7e
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / connection / ConnectionAdapterImpl.java
1 /* Copyright (C)2013 Pantheon Technologies, s.r.o. All rights reserved. */
2
3 package org.opendaylight.openflowjava.protocol.impl.connection;
4
5 import io.netty.channel.Channel;
6 import io.netty.channel.ChannelFuture;
7 import io.netty.util.concurrent.GenericFutureListener;
8
9 import java.util.Collection;
10 import java.util.Collections;
11 import java.util.List;
12 import java.util.concurrent.Future;
13 import java.util.concurrent.TimeUnit;
14
15 import org.opendaylight.controller.sal.common.util.RpcErrors;
16 import org.opendaylight.controller.sal.common.util.Rpcs;
17 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput;
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.EchoReplyInput;
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.ExperimenterInput;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
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.MeterModInput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestMessage;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
57 import org.opendaylight.yangtools.yang.binding.DataContainer;
58 import org.opendaylight.yangtools.yang.binding.DataObject;
59 import org.opendaylight.yangtools.yang.binding.Notification;
60 import org.opendaylight.yangtools.yang.common.RpcError;
61 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
62 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
63 import org.opendaylight.yangtools.yang.common.RpcResult;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 import com.google.common.cache.Cache;
68 import com.google.common.cache.CacheBuilder;
69 import com.google.common.cache.RemovalListener;
70 import com.google.common.cache.RemovalNotification;
71 import com.google.common.collect.Lists;
72 import com.google.common.util.concurrent.SettableFuture;
73
74 /**
75  * @author mirehak
76  * @author michal.polkorab
77  */
78 public class ConnectionAdapterImpl implements ConnectionFacade {
79     
80     /** after this time, rpc future response objects will be thrown away (in minutes) */
81     public static final int RPC_RESPONSE_EXPIRATION = 1;
82
83     protected static final Logger LOG = LoggerFactory
84             .getLogger(ConnectionAdapterImpl.class);
85     
86     private static final String APPLICATION_TAG = "OPENFLOW_LIBRARY";
87     private static final String TAG = "OPENFLOW";
88     private Channel channel;
89     private OpenflowProtocolListener messageListener;
90     /** expiring cache for future rpcResponses */
91     protected Cache<RpcResponseKey, SettableFuture<?>> responseCache;
92     private SystemNotificationsListener systemListener;
93     private boolean disconnectOccured = false;
94
95     protected ConnectionReadyListener connectionReadyListener;
96
97     /**
98      * default ctor 
99      */
100     public ConnectionAdapterImpl() {
101         responseCache = CacheBuilder.newBuilder()
102                 .concurrencyLevel(1)
103                 .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
104                 .removalListener(new ResponseRemovalListener()).build();
105         LOG.info("ConnectionAdapter created");
106     }
107     
108     /**
109      * @param channel the channel to be set - used for communication
110      */
111     public void setChannel(Channel channel) {
112         this.channel = channel;
113     }
114
115     @Override
116     public Future<RpcResult<BarrierOutput>> barrier(BarrierInput input) {
117         return sendToSwitchExpectRpcResultFuture(
118                 input, BarrierOutput.class, "barrier-input sending failed");
119     }
120
121     @Override
122     public Future<RpcResult<EchoOutput>> echo(EchoInput input) {
123         return sendToSwitchExpectRpcResultFuture(
124                 input, EchoOutput.class, "echo-input sending failed");
125     }
126
127     @Override
128     public Future<RpcResult<Void>> echoReply(EchoReplyInput input) {
129         return sendToSwitchFuture(input, "echo-reply sending failed");
130     }
131
132     @Override
133     public Future<RpcResult<Void>> experimenter(ExperimenterInput input) {
134         return sendToSwitchFuture(input, "experimenter sending failed");
135     }
136
137     @Override
138     public Future<RpcResult<Void>> flowMod(FlowModInput input) {
139         return sendToSwitchFuture(input, "flow-mod sending failed");
140     }
141
142     @Override
143     public Future<RpcResult<GetConfigOutput>> getConfig(GetConfigInput input) {
144         return sendToSwitchExpectRpcResultFuture(
145                 input, GetConfigOutput.class, "get-config-input sending failed");
146     }
147
148     @Override
149     public Future<RpcResult<GetFeaturesOutput>> getFeatures(
150             GetFeaturesInput input) {
151         return sendToSwitchExpectRpcResultFuture(
152                 input, GetFeaturesOutput.class, "get-features-input sending failed");
153     }
154
155     @Override
156     public Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(
157             GetQueueConfigInput input) {
158         return sendToSwitchExpectRpcResultFuture(
159                 input, GetQueueConfigOutput.class, "get-queue-config-input sending failed");
160     }
161
162     @Override
163     public Future<RpcResult<Void>> groupMod(GroupModInput input) {
164         return sendToSwitchFuture(input, "group-mod-input sending failed");
165     }
166
167     @Override
168     public Future<RpcResult<Void>> hello(HelloInput input) {
169         return sendToSwitchFuture(input, "hello-input sending failed");
170     }
171
172     @Override
173     public Future<RpcResult<Void>> meterMod(MeterModInput input) {
174         return sendToSwitchFuture(input, "meter-mod-input sending failed");
175     }
176
177     @Override
178     public Future<RpcResult<Void>> packetOut(PacketOutInput input) {
179         return sendToSwitchFuture(input, "packet-out-input sending failed");
180     }
181
182     @Override
183     public Future<RpcResult<Void>> portMod(PortModInput input) {
184         return sendToSwitchFuture(input, "port-mod-input sending failed");
185     }
186
187     @Override
188     public Future<RpcResult<RoleRequestOutput>> roleRequest(
189             RoleRequestInput input) {
190         return sendToSwitchExpectRpcResultFuture(
191                 input, RoleRequestOutput.class, "role-request-config-input sending failed");
192     }
193
194     @Override
195     public Future<RpcResult<Void>> setConfig(SetConfigInput input) {
196         return sendToSwitchFuture(input, "set-config-input sending failed");
197     }
198
199     @Override
200     public Future<RpcResult<Void>> tableMod(TableModInput input) {
201         return sendToSwitchFuture(input, "table-mod-input sending failed");
202     }
203
204     @Override
205     public Future<RpcResult<GetAsyncOutput>> getAsync(GetAsyncInput input) {
206         return sendToSwitchExpectRpcResultFuture(
207                 input, GetAsyncOutput.class, "get-async-input sending failed");
208     }
209
210     @Override
211     public Future<RpcResult<Void>> setAsync(SetAsyncInput input) {
212         return sendToSwitchFuture(input, "set-async-input sending failed");
213     }
214
215     @Override
216     public Future<Boolean> disconnect() {
217         ChannelFuture disconnectResult = channel.disconnect();
218         responseCache.invalidateAll();
219         disconnectOccured = true;
220
221         String failureInfo = "switch disconnecting failed";
222         ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
223         String message = "Check the switch connection";
224         return handleTransportChannelFuture(disconnectResult, failureInfo, errorSeverity, message);
225     }
226
227     @Override
228     public boolean isAlive() {
229         return channel.isOpen();
230     }
231
232     @Override
233     public void setMessageListener(OpenflowProtocolListener messageListener) {
234         this.messageListener = messageListener;
235     }
236     
237     @Override
238     public void consume(DataObject message) {
239         LOG.debug("ConsumeIntern msg");
240         if (disconnectOccured ) {
241             return;
242         }
243         if (message instanceof Notification) {
244             // System events
245             if (message instanceof DisconnectEvent) {
246                 systemListener.onDisconnectEvent((DisconnectEvent) message);
247                 responseCache.invalidateAll();
248                 disconnectOccured = true;
249             } else if (message instanceof SwitchIdleEvent) {
250                 systemListener.onSwitchIdleEvent((SwitchIdleEvent) message);
251             }
252             // OpenFlow messages
253               else if (message instanceof EchoRequestMessage) {
254                 messageListener.onEchoRequestMessage((EchoRequestMessage) message);
255             } else if (message instanceof ErrorMessage) {
256                 messageListener.onErrorMessage((ErrorMessage) message);
257             } else if (message instanceof ExperimenterMessage) {
258                 messageListener.onExperimenterMessage((ExperimenterMessage) message);
259             } else if (message instanceof FlowRemovedMessage) {
260                 messageListener.onFlowRemovedMessage((FlowRemovedMessage) message);
261             } else if (message instanceof HelloMessage) {
262                 LOG.info("Hello received / branch");
263                 messageListener.onHelloMessage((HelloMessage) message);
264             } else if (message instanceof MultipartReplyMessage) {
265                 messageListener.onMultipartReplyMessage((MultipartReplyMessage) message);
266             } else if (message instanceof MultipartRequestMessage) {
267                 messageListener.onMultipartRequestMessage((MultipartRequestMessage) message);
268             } else if (message instanceof PacketInMessage) {
269                 messageListener.onPacketInMessage((PacketInMessage) message);
270             } else if (message instanceof PortStatusMessage) {
271                 messageListener.onPortStatusMessage((PortStatusMessage) message);
272             } else {
273                 LOG.warn("message listening not supported for type: "+message.getClass());
274             }
275         } else {
276             if (message instanceof OfHeader) {
277                 LOG.debug("OFheader msg received");
278                 RpcResponseKey key = createRpcResponseKey((OfHeader) message);
279                 final SettableFuture<RpcResult<?>> rpcFuture = findRpcResponse(key);
280                 if (rpcFuture != null) {
281                     LOG.debug("corresponding rpcFuture found");
282                     List<RpcError> errors = Collections.emptyList();
283                     LOG.debug("before setting rpcFuture");
284                     rpcFuture.set(Rpcs.getRpcResult(true, message, errors));
285                     LOG.debug("after setting rpcFuture");
286                     responseCache.invalidate(key);
287                 } else {
288                     LOG.warn("received unexpected rpc response: "+key);
289                 }
290             } else {
291                 LOG.warn("message listening not supported for type: "+message.getClass());
292             }
293         }
294     }
295
296     /**
297      * sends given message to switch, sending result will be reported via return value
298      * @param input message to send
299      * @param failureInfo describes, what type of message caused failure by sending 
300      * @return future object, <ul>
301      *  <li>if send successful, {@link RpcResult} without errors and successful 
302      *  status will be returned, </li>
303      *  <li>else {@link RpcResult} will contain errors and failed status</li>
304      *  </ul>    
305      */
306     private SettableFuture<RpcResult<Void>> sendToSwitchFuture(
307             DataObject input, final String failureInfo) {
308         LOG.debug("going to flush");
309         ChannelFuture resultFuture = channel.writeAndFlush(input);
310         LOG.debug("flushed");
311         
312         ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
313         String errorMessage = "check switch connection";
314         return handleRpcChannelFuture(resultFuture, failureInfo, errorSeverity, errorMessage);
315     }
316     
317     /**
318      * sends given message to switch, sending result or switch response will be reported via return value
319      * @param input message to send
320      * @param responseClazz type of response
321      * @param failureInfo describes, what type of message caused failure by sending 
322      * @return future object, <ul>
323      *  <li>if send fails, {@link RpcResult} will contain errors and failed status </li>
324      *  <li>else {@link RpcResult} will be stored in responseCache and wait for particular timeout 
325      *  ({@link ConnectionAdapterImpl#RPC_RESPONSE_EXPIRATION}), 
326      *  <ul><li>either switch will manage to answer
327      *  and then corresponding response message will be set into returned future</li>
328      *  <li>or response in cache will expire and returned future will be cancelled</li></ul>
329      *  </li>
330      *  </ul>     
331      */
332     private <IN extends OfHeader, OUT extends OfHeader> SettableFuture<RpcResult<OUT>> sendToSwitchExpectRpcResultFuture(
333             IN input, Class<OUT> responseClazz, final String failureInfo) {
334         LOG.debug("going to flush");
335         SettableFuture<RpcResult<OUT>> rpcResult = SettableFuture.create();
336         RpcResponseKey key = new RpcResponseKey(input.getXid(), responseClazz);
337         responseCache.put(key, rpcResult);
338         ChannelFuture resultFuture = channel.writeAndFlush(input);
339         LOG.debug("flushed");
340         
341         ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
342         String errorMessage = "check switch connection";
343         
344         return handleRpcChannelFutureWithResponse(resultFuture, failureInfo, errorSeverity, 
345                 errorMessage, input, responseClazz, rpcResult, key);
346     }
347
348     /**
349      * @param resultFuture
350      * @param failureInfo
351      * @return
352      */
353     private SettableFuture<RpcResult<Void>> handleRpcChannelFuture(
354             ChannelFuture resultFuture, final String failureInfo, 
355             final ErrorSeverity errorSeverity, final String errorMessage) {
356         
357         final SettableFuture<RpcResult<Void>> rpcResult = SettableFuture.create();
358         LOG.debug("handlerpcchannelfuture");
359         resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
360             
361             @Override
362             public void operationComplete(
363                     io.netty.util.concurrent.Future<? super Void> future)
364                     throws Exception {
365                 LOG.debug("operation complete");
366                 Collection<RpcError> errors = Collections.emptyList();
367                 
368                 if (future.cause() != null) {
369                     LOG.debug("future.cause != null");
370                     RpcError rpcError = buildRpcError(failureInfo, 
371                             errorSeverity, errorMessage, future.cause());
372                     errors = Lists.newArrayList(rpcError);
373                 }
374                 
375                 rpcResult.set(Rpcs.getRpcResult(
376                         future.isSuccess(), 
377                         (Void) null, 
378                         errors)
379                 );
380             }
381         });
382         return rpcResult;
383     }
384     
385     /**
386      * @param resultFuture
387      * @param failureInfo
388      * @param errorSeverity
389      * @param errorMessage
390      * @param input
391      * @param responseClazz
392      * @param key of rpcResponse
393      * @return
394      */
395     private <IN extends OfHeader, OUT extends OfHeader> SettableFuture<RpcResult<OUT>> handleRpcChannelFutureWithResponse(
396             ChannelFuture resultFuture, final String failureInfo,
397             final ErrorSeverity errorSeverity, final String errorMessage,
398             final IN input, Class<OUT> responseClazz, final SettableFuture<RpcResult<OUT>> rpcResult, final RpcResponseKey key) {
399         LOG.debug("handleRpcchanfuture with response");
400         
401         resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
402             
403             @Override
404             public void operationComplete(
405                     io.netty.util.concurrent.Future<? super Void> future)
406                     throws Exception {
407                 
408                 LOG.debug("operation complete");
409                 Collection<RpcError> errors = Collections.emptyList();
410                 if (future.cause() != null) {
411                     LOG.debug("ChannelFuture.cause != null");
412                     RpcError rpcError = buildRpcError(failureInfo, 
413                             errorSeverity, errorMessage, future.cause());
414                     errors = Lists.newArrayList(rpcError);
415                     rpcResult.set(Rpcs.getRpcResult(
416                             future.isSuccess(), 
417                             (OUT) null, 
418                             errors)
419                             );
420                     responseCache.invalidate(key);
421                 } else {
422                     LOG.debug("ChannelFuture.cause == null");
423                     if (responseCache.getIfPresent(key) == null) {
424                         LOG.debug("responcache: key wasn't present");
425                     }
426                 }
427             }
428         });
429         return rpcResult;
430     }
431
432     /**
433      * @param resultFuture
434      * @param failureInfo
435      * @param errorSeverity 
436      * @param message 
437      * @return
438      */
439     private static SettableFuture<Boolean> handleTransportChannelFuture(
440             ChannelFuture resultFuture, final String failureInfo, 
441             final ErrorSeverity errorSeverity, final String message) {
442         
443         final SettableFuture<Boolean> transportResult = SettableFuture.create();
444         
445         resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
446             
447             @Override
448             public void operationComplete(
449                     io.netty.util.concurrent.Future<? super Void> future)
450                     throws Exception {
451                 transportResult.set(future.isSuccess());
452                 if (!future.isSuccess()) {
453                     transportResult.setException(future.cause());
454                 }
455             }
456         });
457         return transportResult;
458     }
459
460     /**
461      * @param cause
462      * @return
463      */
464     protected RpcError buildRpcError(String info, ErrorSeverity severity, String message, 
465             Throwable cause) {
466         RpcError error = RpcErrors.getRpcError(APPLICATION_TAG, TAG, info, severity, message, 
467                 ErrorType.RPC, cause);
468         return error;
469     }
470     
471     /**
472      * @param cause
473      * @return
474      */
475     protected RpcError buildTransportError(String info, ErrorSeverity severity, String message, 
476             Throwable cause) {
477         RpcError error = RpcErrors.getRpcError(APPLICATION_TAG, TAG, info, severity, message, 
478                 ErrorType.TRANSPORT, cause);
479         return error;
480     }
481
482     /**
483      * @param message
484      * @return
485      */
486     private static RpcResponseKey createRpcResponseKey(OfHeader message) {
487         return new RpcResponseKey(message.getXid(), message.getClass());
488     }
489
490     /**
491      * @return
492      */
493     @SuppressWarnings("unchecked")
494     private SettableFuture<RpcResult<?>> findRpcResponse(RpcResponseKey key) {
495         return (SettableFuture<RpcResult<?>>) responseCache.getIfPresent(key);
496     }
497
498     @Override
499     public void setSystemListener(SystemNotificationsListener systemListener) {
500         this.systemListener = systemListener;
501     }
502     
503     @Override
504     public void checkListeners() {
505         StringBuffer buffer =  new StringBuffer();
506         if (systemListener == null) {
507             buffer.append("SystemListener ");
508         }
509         if (messageListener == null) {
510             buffer.append("MessageListener ");
511         }
512         if (connectionReadyListener == null) {
513             buffer.append("ConnectionReadyListener ");
514         }
515         
516         if (buffer.length() > 0) {
517             throw new IllegalStateException("Missing listeners: " + buffer.toString());
518         }
519     }
520
521     static class ResponseRemovalListener implements RemovalListener<RpcResponseKey, SettableFuture<?>> {
522         @Override
523         public void onRemoval(
524                 RemovalNotification<RpcResponseKey, SettableFuture<?>> notification) {
525             SettableFuture<?> future = notification.getValue();
526             if (!future.isDone()) {
527                 LOG.warn("rpc response discarded: " + notification.getKey());
528                 future.cancel(true);
529             }
530         }
531     }
532
533     /**
534      * Class is used ONLY for exiting msgQueue processing thread
535      * @author michal.polkorab
536      */
537     static class ExitingDataObject implements DataObject {
538         @Override
539         public Class<? extends DataContainer> getImplementedInterface() {
540             return null;
541         }
542     }
543     
544     @Override
545     public void fireConnectionReadyNotification() {
546         new Thread(new Runnable() {
547             @Override
548             public void run() {
549                 connectionReadyListener.onConnectionReady();
550             }
551         }).start();
552     }
553     
554     
555     @Override
556     public void setConnectionReadyListener(
557             ConnectionReadyListener connectionReadyListener) {
558         this.connectionReadyListener = connectionReadyListener;
559     }
560     
561 }