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