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