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