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