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